【发布时间】:2019-09-19 23:28:53
【问题描述】:
我正在用 C++ 11 编写一个代码,它会读取一些行并打印每行的第一个单词。我决定使用 getline 和 stringstream。
string line, word;
stringstream ss;
while(somecondition){
getline(cin, line);
ss << line;
ss >> word;
cout << word << endl;
}
我尝试使用以下输入测试这段代码:
a x
b y
c z
预期的输出是:
a
b
c
但实际输出是:
a
xb
yc
有人能解释一下为什么会这样吗?
我尝试过的事情:
ss.clear();在 while 循环中在while循环中初始化字符串为空:
word = "";
似乎没有任何效果,并且都产生相同的输出。
- 但是,当我在 while 循环中声明
stringstream ss;时,它运行良好。
如果有人能解释为什么将 stringstream 声明放在 while 循环之外可能会导致出现额外字符,我将非常高兴。
我还使用了g++ 编译器和--std=c++11。
【问题讨论】:
-
this answer 有什么帮助吗?
-
ss << line;添加到字符串流。 -
而
clear函数并没有像你想象的那样做。
标签: c++ stringstream