C++正确使用 stringstream::str() 吗?
考虑以下 C++ 程序:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main (void)
{
string l1, l2;
int n1, n2;
stringstream ss;
getline(cin, l1);
getline(cin, l2);
cerr << l1 << " " << l2 << endl;
ss.str(l1);
ss >> n1;
ss.str(l2);
ss >> n2;
cerr << n1 << " " << n2 << endl;
return 0;
}
示例输入:
2
3
相应的输出:
2 3
2 0
但我期望的是:
2 3
2 3
如果我在第二次调用 ss.str() 之前插入调用 ss.clear(),则输出就是我所期望的。这真的有必要吗?为什么?
Consider the following C++ program:
#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main (void)
{
string l1, l2;
int n1, n2;
stringstream ss;
getline(cin, l1);
getline(cin, l2);
cerr << l1 << " " << l2 << endl;
ss.str(l1);
ss >> n1;
ss.str(l2);
ss >> n2;
cerr << n1 << " " << n2 << endl;
return 0;
}
Sample input:
2
3
Corresponding output:
2 3
2 0
But I was expecting:
2 3
2 3
If I insert a call ss.clear() before the second call to ss.str(), the output is what I expected. Is this really necessary? And why?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是必要的,因为字符串字符串的第一个输入到达文件末尾。调用
str()
不会清除字符串流上已设置的任何错误标志。您可以在第二个 str() 之前或之后使用clear,只要它在您尝试读取更多数据之前即可。
It is necessary, because the first input from the stringstring hits end of file. Calling
str()
does not clear any error flags that are already set on the stringstream.You can use clear before the second str() or after, just as long as it's before you attempt to read more data.