I want to read a line from stdinand mark it with a space using the class istringstream. But it does not 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 introduce separate separable lines, everything 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 spaces, the strange thing is that 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?
source
share