-
input validation
I have this simple code for input validation where the only options are 1 and 2. But if the user entered a character, the loop becomes never-ending. How do i validate for incorrect input datatype?
Code:
int input;
while (input != 1 && input != 2)
{
cout << endl << "Invalid input! Try again: ";
cin >> input;
}
-
One approach is to read a line into a string, use that string to create a stringstream, then parse the contents of the stringstream:
Code:
int input;
string line;
while (getline(cin, line))
{
stringstream ss(line);
if (ss >> input && ss.eof())
{
break;
}
else
{
cout << "\nInvalid input! Try again: ";
}
}
Note that if the user triggers end of file in my example (unlikely, but possible), the loop will terminate without having read into input, so it may be wise to provide input with a default value.
-
what about the validation for
Code:
input != 1 && input != 2
now that the datatype is stringstream, how do i check if the input is 1 or 2?
-
The datatype is still int. The stringstream is just part of the processing to validate the input. This part parses the string for the input: ss >> input && ss.eof()
So, how are you going to add the extra validation for the value of the parsed input?
-
This is what i got.
Code:
while (getline(cin, line))
{
stringstream ss(line);
if (ss >> input && ss.eof() && (input == 1 || input == 2))
{
break;
}
else
{
cout << "\nInvalid input! Try again: ";
}
}
-