raz
raz

Reputation: 492

Program goes into infinite loop in case of wrong input

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;

}

Upvotes: 0

Views: 203

Answers (2)

Ayushi Jha
Ayushi Jha

Reputation: 4023

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.

Upvotes: 3

Kieren Pearson
Kieren Pearson

Reputation: 470

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();
}

Upvotes: 2

Related Questions