简体   繁体   中英

C++ iostream iostate

#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
using namespace std;
int main()
{
    int ival;
    while(cin >> ival, !cin.eof())
    {
        if(cin.bad())
            throw runtime_error("IO stream corrupted");
        if(cin.fail())
        {
            cerr<< "bad data,try again"<<endl;
            cin.clear(istream::failbit);
            continue;
        }
    }
}

My English is poor and apologize for it. after compiled this code and run it,i input and "a" in the console, and it is in the dead loop, i can't input another alphabet in it? who can tell me what happened??

The problem is that std::basic_ios::clear doesn't actually clear the bit you provide. It sets the bits you provide.

Two problems here:

  1. As described in http://en.cppreference.com/w/cpp/io/basic_ios/clear std::basic_ios::clear doesn't clear the bit you provide, it sets it . Thus you need to set the goodbit on.

  2. You need to flush the stream to prevent the newline from spoiling your loop

This should work in the intended way

#include <iostream>
#include <fstream>
#include <sstream>
#include <stdexcept>
#include <limits>
using namespace std;
int main()
{
  int ival;
  while(cin >> ival, !cin.eof())
  {
    cout<< cin.rdstate()<<endl;
    if(cin.bad())
      throw runtime_error("IO stream corrupted");
    if(cin.fail())
    {
      cout<< "bad data,try again"<<endl;
      cin.clear(istream::goodbit); // Set the goodbit
      cin.ignore (std::numeric_limits<std::streamsize>::max(), '\n'); 
      continue;
    }
  }
}

http://ideone.com/enFBjA

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM