用stringstream给字符串赋值
发现和想的不一样
简单地说,罢工了
推敲出以下例子,以后给我乖乖工作!:D
#include <iostream> #include <sstream> #include <bitset> using namespace std; string getState(stringstream& ss) { ostringstream os; //显示数据和三个标志位(badbit、failbit、eofbit) os << ss.str() << "(bfe:" << std::bitset<3>(ss.rdstate()) << ")"; return os.str(); } void main() { stringstream ss; string s1; ss.str("aa"); cout << getState(ss) << endl; // aa(bfe:000) ss << "a11"; cout << getState(ss) << endl; //a11(bfe:000) //初始值在数据流入的时候,被覆盖 ss << " a22"; cout << getState(ss) << endl; //a11 a22(bfe:000) //现在正常流入数据 ss >> s1; cout << getState(ss) << ", " << s1 << endl;//a11 a22(bfe:000), a11 //输出第1个数据 ss << " a33"; cout << getState(ss) << endl; //a11 a22 a33(bfe:000) ss >> s1; cout << getState(ss) << ", " << s1 << endl;//a11 a22 a33(bfe:000), a22 //输出第2个数据 ss >> s1; cout << getState(ss) << ", " << s1 << endl;//a11 a22 a33(bfe:001), a33 //数据全部输出,eof位变成1,罢工啦 ss << " a44"; cout << getState(ss) << endl;//a11 a22 a33(bfe:101) //罢工以后拒绝接收数据,bad位也是1啦 s1 = "<none>"; ss >> s1; cout << getState(ss) << ", " << s1 << endl;//a11 a22 a33(bfe:111), <none> //罢工了也不会输出数据,fail位也变成1 ss.clear(); //重置流状态,并不会清除数据 cout << getState(ss) << endl;//a11 a22 a33(bfe:000) //开工! ss << " a55"; cout << getState(ss) << endl;//a11 a22 a33 a55(bfe:000) ss >> s1; cout << getState(ss) << ", " << s1 << endl;//a11 a22 a33 a55(bfe:001), a55 //并不会重头开始取数据 system("pause"); }