缘起
#include <iostream> #include <sstream> using namespace std; int main() { istringstream iss; string str1, str2, str3, str4, str5, str6; iss.str("I love you"); iss >> str1 >> str2 >> str3; cout << str1 << " " << str2 << " "<< str3 << endl; iss.str("I hate you"); iss >> str4 >> str5 >> str6; cout << str4 << " " << str5 << " "<< str6 << endl; }
期待输出
可以结果是
问题
没有输出“I hate you"。究竟是什么原因导致 流没有输出到字符串中?
一番折腾知道,此时流的eof为1(已经达到结束符),此时必须用函数clear()把所有的状态值设为有效状态值。经过修改程序如下:
#include <iostream> #include <sstream> using namespace std; int main() { istringstream iss; string str1, str2, str3, str4, str5, str6; iss.str("I love you"); cout << "before" << iss.str() << endl; iss >> str1 >> str2 >> str3; cout << str1 << " " << str2 << " "<< str3 << endl; cout << "eofbit:" << iss.eof() << endl; iss.clear(); cout << "eofbit:" << iss.eof() << endl; iss.str("I hate you"); cout << "after:" << iss.str() << endl; iss >> str4 >> str5 >> str6; cout << str4 << " " << str5 << " "<< str6 << endl; }
正确结果
程序用到知识
本文转自jihite博客园博客,原文链接:http://www.cnblogs.com/kaituorensheng/p/3240775.html,如需转载请自行联系原作者