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; }
相应的输出: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; },c++,stringstream,C++,Stringstream,相应的输出: 2 3 2 0 但我期待着: 2 3 2 3 如果我在第二次调用ss.str()之前插入一个调用ss.clear(),那么输出就是我所期望的。这真的有必要吗?为什么呢?这是必要的,因为stringstring的第一个输入到达了文件的末尾。调用str()不会清除stringstream上已设置的任何错误标志 ss.str(l1); ss >> n1; // Reads the entire buffer, hits the end of buffer and se
2 3
2 0
但我期待着:
2 3
2 3
如果我在第二次调用ss.str()之前插入一个调用ss.clear(),那么输出就是我所期望的。这真的有必要吗?为什么呢?这是必要的,因为stringstring的第一个输入到达了文件的末尾。调用
str()
不会清除stringstream上已设置的任何错误标志
ss.str(l1);
ss >> n1; // Reads the entire buffer, hits the end of buffer and sets eof flag
ss.str(l2); // Sets the string, but does not clear error flags
ss >> n2; // Fails, due to at EOF
可以在第二个str()之前或之后使用clear,只要是在尝试读取更多数据之前
ss.str(l1);
ss >> n1; // Reads the entire buffer, hits the end of buffer and sets eof flag
ss.str(l2); // Sets the string, but does not clear error flags
ss >> n2; // Fails, due to at EOF