使用c++ 的stream遇到的问题

     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;
eofbitEnd-Of-File reached while performing an extracting operation on an input stream.
failbitThe last input operation failed because of an error related to the internal logic of the operation itself.
badbitError due to the failure of an input/output operation on the stream buffer.
goodbitNo error. Represents the absence of all the above (the value zero).

发现eof是文档结尾,所以str的结尾不会置上eofbit标志位,但由于出错,failbit位会被置上。

如果之后还要使用这个stringstream对象ss,一定要先ss.clear()将错误信息清空,stringstream不会自动清空。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值