cin.clear()的使用注意

#include <iostream>

using namespace std;

 

    int main()

    {

         int ival=0;

    // read cin and test only for EOF; loop is executed even if there are other IO failures

    while (cin >> ival,!cin.eof ()) {

         cin.clear();   //用clear()让cin的状态为正常,但是内存这时未清空

         cin.sync();    //加入了这句后,程序可以正常运行,不加以前不行,程序会不等输入就直接进入循环内部,网上说是因为内存未清空

         cout<<"istream::failbit is "<<istream::failbit<<std::endl ;

     cout<<"cin.good() is"<<cin.good()<<std::endl ;

        if (cin.bad())         // input stream is corrupted; bail out

            throw runtime_error("IO stream corrupted");

        if (cin.fail()) {                        // bad input

            cerr<< "bad data, try again"<<endl;

              // warn the user

              cout<<"cin.good() before cin.clear() is"<<cin.good()<<std::endl ;

              cin.clear();         // reset the stream

              cin.sync();

              //cin.clear(istream::failbit);

              cout<<"cin.good() after cin.clear()is"<<cin.good()<<std::endl ;

            continue;                            // get next input

        }

        // ok to process ival

    }

 

 

        return 0;

    }

/*这个完全是按程序写的,但是cin.clear()没起作用,再进while时,程序没有读就认为cin是坏的,说明cin没有被清空;

无论CIN.GOOD()运行结果如何,程序都会进入cin.fail();会不停地出bad data

把while改为while(cin>>ival)后会直接退出,不会再进入循环,因为这时cin>>ival不为真值,就直接运行return 0了。

但我的目的是要让cin接受下一个输入,所以再用while (cin >> ival,!cin.eof ())

加入cin.sync();

*/

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值