c++的stream系列类是c++复杂性的一个体现点。总体来讲,复杂性安全性超过c,但速度低于c。
我是由于处理的数据量小,但数据形式不固定,而c++的stream有助于格式检查,所以使用了c++的stream。下面开始。
1.状态判断问题
我使用的代码大致是:
string str;
stringstream ss;
ifstream infile;
int a;
...
getline(str, infile);
ss.str(str);
while(!ss.eof()) ss>>a;
看起来无错,还把数依次读出来。但问题是每次while结束后,ss.fail()总是true. 经过翻看源码及文档
typedef unsigned int iostate;
typedef iostate io_state;
static const iostate badbit = 0x1;
static const iostate eofbit = 0x2;
static const iostate failbit = 0x4;
static const iostate goodbit = 0x0;
eofbit | End-Of-File reached while performing an extracting operation on an input stream. |
failbit | The last input operation failed because of an error related to the internal logic of the operation itself. |
badbit | Error due to the failure of an input/output operation on the stream buffer. |
goodbit | No error. Represents the absence of all the above (the value zero). |
发现eof是文档结尾,所以str的结尾不会置上eofbit标志位,但由于出错,failbit位会被置上。
如果之后还要使用这个stringstream对象ss,一定要先ss.clear()将错误信息清空,stringstream不会自动清空。