I want to read a line from stdin
and tokenize it by whitespace, using the istringstream
class. But it doesn't work as expected:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string input_line;
istringstream input_stream;
string word;
cout << "> ";
getline(cin, input_line);
input_stream.str(input_line);
input_stream >> word;
cout << " line: " << input_line << endl;
cout << " stream: " << input_stream.str() << endl;
cout << " word: " << word << endl;
cout << "> ";
getline(cin, input_line);
input_stream.str(input_line);
input_stream >> word;
cout << " line: " << input_line << endl;
cout << " stream: " << input_stream.str() << endl;
cout << " word: " << word << endl;
}
If I enter whitespace separated lines, all is fine:
> aa bb
line: aa bb
stream: aa bb
word: aa
> xx yy
line: xx yy
stream: xx yy
word: xx
However, if I enter lines without whitespace, strangely the >>
operator correctly reads from the stream the first time, but not the second time:
> aa
line: aa
stream: aa
word: aa
> xx
line: xx
stream: xx
word: aa
What am I doing wrong?