loop error when numbers entered
why this loop executes 3 times when a number is entered? I only want 's' or 'm' to be accepted.. how could I fix this?
cout << "Are you married or single (m/s): ";
cin >> status;
status = tolower(status); //converting to lower case
//validating imput for marital status
while((status != 'm') &&am开发者_JAVA百科p; (status != 's'))
{
cout << "Sorry, you must enter \"m\" or \"s\" \n"
<< "Are you married or single (m/s): ";
cin >> status;
status = tolower(status);
}
Your variable status
is probably declared as:
char status;
So, cin >> status
reads a single character from the input. However, you probably typed more than one because the input is buffered and you needed to press Enter.
Instead, use this declaration:
string status;
which will get the whole line of input, and then you can inspect the characters within the line.
You can use getchar()
to save into status,
it reads only one character from buffer..
cout << "Are you married or single (m/s): ";
getchar(status);
//validating imput for marital status
while((status != 'm') || (status != 's')) //status can be a male OR a female
{
cout << "Sorry, you must enter \"m\" or \"s\" \n"
<< "Are you married or single (m/s): ";
getchar(status);
}
精彩评论