Hi,

i accidentally given input as character for a integer variable.....then the program went crazy and just flooded the console.....

so, is there any way to handle this exception......and how to achieve that

thank you

you have to check for error, and if it occurs clear the input buffer

See this thread about how to clear the input buffer.

#include <iostream>
#include <limits>
using std::cin;
using std::cout;

int main()
{
    int c;
    while(true)
    {
        cout << "Enter a number\n";
        cin >> c;
        if( cin.fail() )
        {
            cout << "Oops!\n";
            cin.clear();
            cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
        }
        else
            break;
    }
}

Edited 6 Years Ago by Ancient Dragon: n/a

you have to check for error, and if it occurs clear the input buffer

See this thread about how to clear the input buffer.

#include <iostream>
#include <limits>
using std::cin;
using std::cout;

int main()
{
    int c;
    while(true)
    {
        cout << "Enter a number\n";
        cin >> c;
        if( cin.fail() )
        {
            cout << "Oops!\n";
            cin.clear();
            cin.ignore ( std::numeric_limits<std::streamsize>::max(), '\n' );
        }
        else
            break;
    }
}

thank you very much friend......it's perfectly working

You corrupted your input stream, you need to reset it and remove the offending char(s).
You will need to use ios::good() or ios::fail() to detect the stream corruption. You will then have to use ios::clear() to reset the stream. Then you will need to use istream::ignore() to "throw away" the bad input.

okay....i got it.......thank you

This question has already been answered. Start a new discussion instead.