I have a program which asks the user to input an integer in the range [0,2]. I used the following link as a guide.
Good input validation loop using cin - C++
However, when the user presses enter without inputting data the cursor simply goes to the next line in the command prompt whereas I would prefer it to prompt the user to enter a valid number. Does prompting the user in this case make sense, or is there a reason not to implement validation as single line input to begin with? In the case of strings I would use getline to solve this, should I use that somehow in this case? Here is my code, based on the above link:
#include <iostream>
int main()
{
int answeredNumber;
while(1)
{
std::cout << "Enter your answer: ";
if(std::cin >> answeredNumber && answeredNumber >= 0 && answeredNumber <= 2)
{
break;
}
else
{
std::cout << "Please enter a valid answer: " ;
std::cin.clear();
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
}
}
system("pause");
}