cin.clear()的使用注意

    技术2022-05-20  36

    #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();

    */

     


    最新回复(0)