I've redirected "cin" to read from a file stream cin.rdbug(inF.rdbug())
When I use the extraction operator it reads until it reaches a white space character.
Is it possible to use another delimiter? I went through the api in cplusplus.com, but didn't find anything.
It is possible to change the inter-word delimiter for
cin
or any otherstd::istream
, usingstd::ios_base::imbue
to add a customctype
facet
.If you are reading a file in the style of /etc/passwd, the following program will read each
:
-delimited word separately.This is an improvement on Robᵩ's answer, because that is the right one (and I'm disappointed that it hasn't been accepted.)
What you need to do is change the array that
ctype
looks at to decide what a delimiter is.In the simplest case you could create your own:
On my machine
'\n'
is 10. I've set that element of the array to the delimiter value:ctype_base::space
. Actype
initialized withfoo
would only delimit on'\n'
not' '
or'\t'
.Now this is a problem because the array passed into
ctype
defines more than just what a delimiter is, it also defines leters, numbers, symbols, and some other junk needed for streaming. (Ben Voigt's answer touches on this.) So what we really want to do is modify amask
, not create one from scratch.That can be accomplished like this:
A
ctype
initialized withbar
would delimit on'\n'
and':'
but not' '
or'\t'
.You go about setting up
cin
, or any otheristream
, to use your customctype
like this:You can also switch between
ctype
s and the behavior will change mid-stream:If you need to go back to default behavior, just do this:
Live example
For strings, you can use the
std::getline
overloads to read using a different delimiter.For number extraction, the delimiter isn't really "whitespace" to begin with, but any character invalid in a number.