0

I am trying to check the input value, and I run this program below. But when I give a wrong input it goes into infinite loop. I tried the cin.clear(); but still it goes to infinite loop. Please can anyone give me a solution for this.

#include<iostream>
using namespace std;

int main()
{
    int c=0;
    cout<<"in test"<<endl;
    //cin.clear();
    cin>>c;

    if(cin.fail())
        {
            cout<<"please try again"<<endl;
            main();
        }

    else
        cout<<"c = "<<c<<endl;

    return 0;

}
Emil Laine
  • 41,598
  • 9
  • 101
  • 157
raz
  • 482
  • 1
  • 5
  • 17

2 Answers2

3

Use cin.ignore() after cin.clear() to remove the invalid input from stream buffer. Using cin.clear() does not remove the previous input, so it keeps going into an infinite loop. cin.clear() only resets the state, i.e., the error flags etc.

Try this:

    cin.ignore(INT_MAX,'\n');

It clears till the first newline is encountered.

Ayushi Jha
  • 4,003
  • 3
  • 26
  • 43
  • I tried according to your suggestion, but the problem is if i give (for example --- >> an input abcd) it shows please try again for three times. is it possible to clear the wrong input in one time. – raz Jun 20 '15 at 13:45
2

First:

You cannot call the main() function from anywhere within your program.

Second:

Try a while loop like this:

while (cin.fail())
{
    cout << "Please try again" << endl;
    cin.clear();
    cin.ignore();
}
Kieren Pearson
  • 416
  • 3
  • 15