1

I'm trying to learn C++ from an older edition of the Primer, and tried to execute some of their code relating to iostream objects, which gave me some trouble:

#include <iostream>
#include <cstdlib>
using namespace std;

int main(int argc, char *argv[])
{
    int ival;

    try
    {
        while (cin >> ival, !cin.eof())
        {
            if (cin.bad())
                throw runtime_error("IO stream corrupted");
            if (cin.fail())
            {
                cerr << "Invalid input - try again";
                cin.clear(iostream::failbit);
                continue;
            }
            else
                cout << ival << endl;
        }

        return EXIT_SUCCESS;
    }

    catch(runtime_error err)
    {
        cout << err.what();
        return EXIT_FAILURE;
    }
}

When this program encounters an invalid input, it outputs "Invalid input - try again" without stopping, signaling that cin.clear(iostream::failbit) doesn't actually "clear" cin's failbit. I also tried just using cin.clear() to no avail. So my question is, how do I return cin to a non-error state?

  • You didn't actually get rid of the bad input. – chris Jun 09 '13 at 17:32
  • So should I flush the buffer? – detectivecalcite Jun 09 '13 at 17:36
  • To whatever degree you need to, yes. One common way is `std::cin.ignore(std::numeric_limits::max(), '\n');` – chris Jun 09 '13 at 17:39
  • Still having trouble with using the ignore function, then cin.clear with no arguments: using `cerr << "Bad input - try again" << endl; cin.ignore(numeric_limits::max(), '\n'); cin.clear();` still causes the cerr to keep outputting – detectivecalcite Jun 11 '13 at 05:04
  • Ah, never mind, I figured it out myself - the cin.ignore() function only actually works if the stream is in good condition - cin.clear() needs to be called first. Thanks for the help anyways! – detectivecalcite Jun 11 '13 at 05:07

1 Answers1

0

If I'm not mistaken, cin.clear(iostream::failbit) sets the new state to fail. You should first get rid of that part of the input that is causing the problems and then use cin.clear() or cin.clear(iostream::goodbit).

For more information, look here: http://www.cplusplus.com/reference/ios/ios/clear/

someone
  • 361
  • 2
  • 3
  • 13