I ran into a problem while trying to validate my user input. Here's my code:
#include <iostream>
#include <string>
using namespace std;
int main()
{
string choice;
cout << "Please type something: ";
cin >> choice;
cin.ignore();
while (choice != "1" && choice != "2" && choice != "3" && choice != "4" && choice != "5")
{
cout << "Incorrect choice! Please input a valid number: >_";
cin >> choice;
cin.ignore();
}
return 0;
}
When I input "wronginput", that input fell in the while loop and displayed
Incorrect choice! Please input a valid number: >_
Which is good. However, when I try "wrong input", I get a "weird" version of it:
Incorrect choice! Please input a valid number: >_ Incorrect choice! Please input a valid number: >_
My guess is that the space in between is the culprit. Is there any way for me to fix this? Thank you.
cinreads one word at a time, separated by whitespace. When you pass multiple words, they get queued up and processed in order.getlineinstead