I have an input text file. The first line has two int
numbers a
and b
, and the second line is a string. I want to use formatted input to do file >> a >> b
, and then unformatted input to get the characters of the string one by one. In between the two steps, I need to skip over the '\n'
character at the end of the first line. I used
while(file.get()<=' ' && !file.eof()); // skip all unprintable chars
if(!file.eof()) file.unget(); // keep the eof sign once triggered
to make the input format more flexible. The user can now separate the numbers a
and b
from the string using an arbitrary number of empty lines '\n'
, tab keys '\t'
, and/or space keys ' '
-- the same freedom he has to separate the numbers a
and b
. There's even no problem reading in Linux a text file copied from Windows when every end of line now becomes "\r\n"
.
Is there an ifstream
function that does the same thing (skip all chars <=' '
until the next printable char or EOF
is reached)? The ignore
function does not seem to do that.
Yes, there is:
std::ws
manipulator. It skips whitespace characters until a non-whitespace is found or end of stream is reached.. It is similar to use of whitespace character inscanf
format string.In fact, it is used by formatted input before actually starting to parse characters.
You can use it like that: