0

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

3
Contributors
4
Replies
5
Views
7 Years
Discussion Span
Last Post by neoraghav
0

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 by Ancient Dragon: n/a

0

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

0

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.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.