简体   繁体   English

C ++ iostream iostate

[英]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? 编译完这段代码并运行后,我在控制台中输入和“a”,并且它处于死循环中,我不能在其中输入另一个字母表? who can tell me what happened?? 谁能告诉我发生了什么?

The problem is that std::basic_ios::clear doesn't actually clear the bit you provide. 问题是std::basic_ios::clear实际上并没有清除你提供的位。 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 . http://en.cppreference.com/w/cpp/io/basic_ios/clear std::basic_ios::clear中所述, 不会清除您提供的位, 而是设置它 Thus you need to set the goodbit on. 因此,您需要设置好goodbit

  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 http://ideone.com/enFBjA

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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