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

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


        
6条回答
  •  温柔的废话
    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.

提交回复
热议问题