Tamas Koos
Tamas Koos

Reputation: 1063

C++ - Check cin for mistakes

I have a while loop that restarts if the users inputs something wrong.

do{
    cerr<<"Input the numbers divided by a space"<<endl;
    cin>>number1>>number2;
    hiba=(cin.fail() || number1<1 || number1>100 || number2<1 || number2>100);
    if(fail){
        getline(cin, sz);
        cerr<<"Wrong input"<<endl;
    }
}while(fail);

Both variables are integers and it works if the numbers are either below 0 or above 100, but it doesn't work if the user inputs a character, because it starts an infinite loop.

Upvotes: 0

Views: 106

Answers (2)

r-sniper
r-sniper

Reputation: 1483

Try this

int main()
{
    int tanulokszama,versenyekszama;
    bool hiba;
    string sz;
    do{
        cerr<<"Adja meg az elsõ sort!"<<endl;
        cin>>tanulokszama>>versenyekszama;
        hiba=(cin.fail() || tanulokszama<1 || tanulokszama>100 || versenyekszama<1 || versenyekszama>100);
        if(hiba){
            cin.clear();
            cin.ignore(std::numeric_limits<streamsize>::max(),'\n');
            //getline(cin, sz);
            cerr<<"Rossz adatot adott meg!"<<endl;
        }
    }while(hiba);
}

Note:

Dont forget to include

 #include<limits> 

Upvotes: 2

theVoid
theVoid

Reputation: 743

You should use the ignore() and clear() functions to clear the stream and ignore anything until '\n'.

Try this:

do{
    cerr<<"Adja meg az elsõ sort!"<<endl;
    cin>>tanulokszama>>versenyekszama;
    hiba=(cin.fail() || tanulokszama<1 || tanulokszama>100 || versenyekszama<1 || versenyekszama>100);
    if(hiba){
        cin.clear();//clear the error flags of the stream
        cerr<<"Rossz adatot adott meg!"<<endl;
        cin.ignore( 256, '\n');//ignore until '\n'
    }
}while(hiba);

Or even better include limits header file and use the following:

#include <limits>//add this to your includes
do{
    cerr<<"Adja meg az elsõ sort!"<<endl;
    cin>>tanulokszama>>versenyekszama;
    hiba=(cin.fail() || tanulokszama<1 || tanulokszama>100 || versenyekszama<1 || versenyekszama>100);
    if(hiba){
        cin.clear();//clear the error flags of the stream
        cerr<<"Rossz adatot adott meg!"<<endl;
        cin.ignore( numeric_limits<streamsize>::max(), '\n');//extract anything until the '\n' occurs
    }
}while(hiba);

Upvotes: 1

Related Questions