0

Hello I want to simply get user input as an integer from 1- infinity, I can enter something like 0, -1, -20 and my function handles this error properly and simply asks the user to renter once. When I enter a string or character the terminal is spammed with this reprint message. How do I fix this?

int numOfUsers(){
    int x = 0;
    int numPlayers;
    cout << "how many users want to play basketball? please enter a number above 1";
    cin >> numPlayers;
    while(x==0){        
        if (((numPlayers % 1) == 0) && (numPlayers >= 2)){
            x++;                               
        } else {
            cout << "\nplease enter a valid number of players\n";
            cin >> numPlayers;
        }
    }
    return numPlayers;
}
ahmed
  • 341
  • 2
  • 9
  • Read the integer using [std::from_chars](https://en.cppreference.com/w/cpp/utility/from_chars), for example. Another option would be to read it as a string, and try-catch an `std:stoi` of that string into `numPlayers`. – rturrado Jan 18 '23 at 23:19

0 Answers0