+ 1

C++ how to check user input?

how do i check a user input if it's in words? https://code.sololearn.com/c2dQz53LnBwN/?ref=app I did this but it didn't work (works on computer)

30th May 2017, 3:13 AM
Kyroh
Kyroh - avatar
2 Réponses
+ 8
Adding to @Rrestoring faith's answer: You can also make the user input 1, 2 or 3 which corresponds to specific selections by displaying a menu, although it wouldn't work as expected on SL due to console apps having prompt input instead of live console input query. E.g. std::cout << "Please select an option" << std::endl; std::cout << "1) Rock " << std::endl; std::cout << "2) Paper " << std::endl; std::cout << "3) Scissors " << std::endl; std::cin >> selection; if (std::cin.fail() || (selection < 1 || selection > 3)) { std::cin.clear(); std::cin.ignore(512, '\n'); std::cout << "Invalid input."; } else { //codes }
30th May 2017, 4:18 AM
Hatsy Rei
Hatsy Rei - avatar
+ 5
You used a String to get the users input. That's all you really need, you can assume the user entered words. Although, you can check if the user enters numbers by Seeing if you can cast it to a number. Why not just tell the user if input is invalid? In other words, if he does NOT enter "rock', "scissors" or "paper". This can easily be achieved with an else statement. I notice you're writing 'if' 'if' 'if' You should be using else if appropriately like this: if(user == "paper") { } else if(user == "scissors") { } else if(user == "rock") { } else { // that way you can do this! 😊 cout << "Invalid input!"; } You can also make the users input all lowercase letters, that way you don't have to worry about the user entering uppercase letters by writing if(user == "ROCK"). By making it lowercase if(user == "rock") won't have any capital issues.
30th May 2017, 3:35 AM
Rrestoring faith
Rrestoring faith - avatar