0

its my first day of learning c++ and i am encountering the problem that if i accidentaly enter a str or char in an int input it starts an infine loop and doesn't allows to enter another set of values please help.

    while(true){
    int a,b;
    cout<<"enter you numbers seperated by space:: ";
    cin>>a>>b;
    if (isdigit(a) and isdigit(b)){        
        cout<<"enter a for sum and s for subtraction";
        string ans;
        cin>>ans;
        if (ans=="a"){
            cout<<"sum is: "<<a+b<<endl;
        }
        else if (ans=="s"){
            cout<<"difference is: "<<a-b<<endl;
        }
        else{
            cout<<"wrong choice!"<<endl;
        }
    }
    else{
        cout<<"wrong input!!";
    }
}
463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185
  • 1
    It is pointless (and wrong) to use `isdigit` on something you have read as `int`. This function is used for *character* classification. – Eugene Sh. Dec 15 '21 at 15:08
  • An `int` is always an int regardless if the input failed. – drescherjm Dec 15 '21 at 15:12
  • `isdigit()` and other character classification functions (`isalpha()`, `ispunct()` etc.) take `int` as a parameter, but what they actually want is a `char` converted to `unsigned char`. The reasons for this is mostly historic (they wanted to make room for `EOF` as valid input), and might be confusing at first sight. As others have said, `int a; std::cin >> a;` will refuse to read anything that isn't a decimal value in the first place. – DevSolar Dec 15 '21 at 15:17
  • Note that this would only "work" with numbers between 48 and 57. Think some more about the difference between digits (symbols) and numbers (what those symbols can represent). – molbdnilo Dec 15 '21 at 15:22
  • I originarlly wanted to use not isdigit() like in python but i didn't know how so i tried to do it this way. – Ketan Choudhary Dec 15 '21 at 16:28

0 Answers0