我想从stdin
读取一行,并使用istringstream
类通过空格对其进行标记。但它没有按预期工作:
#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;
}
如果我输入空格分隔的行,一切都很好:
> aa bb
line: aa bb
stream: aa bb
word: aa
> xx yy
line: xx yy
stream: xx yy
word: xx
但是,如果我输入的行没有空格,奇怪的是>>
运算符第一次正确地从流中读取,而不是第二次:
> aa
line: aa
stream: aa
word: aa
> xx
line: xx
stream: xx
word: aa
我做错了什么?