Why the following c++ code keeps output “bad data, try again”?

后端 未结 6 1979
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 21:34
int main()
{
        int temp;
        while (cin>>temp, !cin.eof())
        {
                if (cin.bad())
                {
                        throw r         


        
相关标签:
6条回答
  • 2021-01-14 22:00

    The ios::clear() method actually replaces the stream control state bits with its argument. You're setting cin's control state to fail every time you issue cin.clear(istream::failbit);.

    You should simply call cin.clear(); instead, without arguments. That will reset the stream's control state to good.

    EDIT: Oh my god, I forgot.

    You also need to call istream::ignore() to discard the invalid x token you've just entered, since clear() doesn't flush pending input:

    if (cin.fail()) {
        cerr << "bad data, try again\n";
        cin.clear();
        cin.ignore(numeric_limits<streamsize>::max(), '\n');
        continue;
    }
    
    0 讨论(0)
  • 2021-01-14 22:05

    Because your loop will end only when end-of-file is reached. But if you try to read a number where there is an alpha character, cin will fail but eof will never be reached. It will fail to read the number over and over again.

    0 讨论(0)
  • 2021-01-14 22:12

    This has to do with data still being in the input buffer. cin.clear() is simply clearing the error state of cin rather than clearing the buffer. Try doing something like this:

    int main()
    {
            int temp;
            while (cin>>temp, !cin.eof())
            {
                    if (cin.bad())
                    {
                            throw runtime_error("IO stream corrupted");
                    }
    
                    if (cin.fail())
                    {
                            cerr<<"bad data, try again";
                            cin.clear();
                            cin.sync();
                            continue;
                    }
            }
    
            return 0;
    }
    

    cin.sync() will effectively clear the buffer for you. See http://www.cplusplus.com/reference/iostream/istream/sync/ for more information on it.

    0 讨论(0)
  • 2021-01-14 22:14

    You didn't clear() the stream.

    0 讨论(0)
  • 2021-01-14 22:16

    Because x is not an integer, the operator>> operator doesn't read anything, so when you clear the bit and try again, the same thing results.

    0 讨论(0)
  • 2021-01-14 22:19

    If you use formatted input/output the data must match. x is not an integer. Try to enter 5 Enter. Or define temp as std::string.

    0 讨论(0)
提交回复
热议问题