I need to read input from standard input until a space or a TAB is pressed.
Eventually, I need to hold the input in a std::string
object.
I need to read input from standard input until a space or a TAB is pressed.
Eventually, I need to hold the input in a std::string
object.
You can have
std::cin
to stop reading at any designated character usingI don't know if you can easily get it to work with two characters though.
The simple answer is that you can't. In fact, the way you've formulated the question shows that you don't understand
istream
input: there's no such thing as “pressed” inistream
, because there's no guarantee that the input is coming from a keyboard.What you probably need is
curses
orncurses
, which does understand keyboard input; console output and the rest.It seems that the solution to this is, indeed, a lot easier using
scanf("%[^\t ]", buffer)
. If you want to do it using C++ IOStreams I think the nicest to use option is to install astd::locale
with a modifiedstd::ctype<char>
facet which uses a modified interpretation of what is considered to be a space and then read astd::string
(see e.g. this answer I gave for a similar problem). Independent of whether you are using a C or a C++ approach you probably need to turn off line buffering on the standard input if you want to find out about the space or the tab when it entered rather than when the entire line is given to your program.use scanf for this:
A simple code:
Since a tab counts as whitespace, you are asking to extract the first token from the stream. This is very easy in C++, as token extraction is already the default behaviour of the
>>
operator:(The error can only occur in arcane circumstances, e.g. when the input file descriptor is already closed when the program starts.)