Tamas Koos Tamas Koos - 6 days ago 5
C++ Question

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.

Answer

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();
            //getline(cin, sz);
            cerr<<"Rossz adatot adott meg!"<<endl;
        }
    }while(hiba);
}
Comments