Zhuoran He Zhuoran He - 1 year ago 74
C++ Question

Switching from formatted to unformatted input in C++

I have an input text file. The first line has two

, 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
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
from the string using an arbitrary number of empty lines
, tab keys
, and/or space keys
' '
-- the same freedom he has to separate the numbers
. There's even no problem reading in Linux a text file copied from Windows when every end of line now becomes

Is there an
function that does the same thing (skip all chars
<=' '
until the next printable char or
is reached)? The
function does not seem to do that.

Answer Source

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 in scanf format string.

In fact, it is used by formatted input before actually starting to parse characters.

You can use it like that:

int x;
std::string str;
std::cin >> x >> std::ws;
std::getline(std::cin, str);
//std::vector<int> vec;
for(auto& e: vec) {
    std::cin >> e;
std::getline(std::cin >> std::ws, str);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download