为什么这个循环在输入数字时执行3次?我只想要's'或'm'被接受..我怎么能解决这个问题?
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') && (status != 's'))
{
cout << "Sorry, you must enter \"m\" or \"s\" \n"
<< "Are you married or single (m/s): ";
cin >> status;
status = tolower(status);
}
答案 0 :(得分:6)
您的变量status
可能声明为:
char status;
因此,cin >> status
从输入中读取单个字符。但是,您可能键入了多个,因为输入已缓冲,您需要按Enter键。
相反,请使用此声明:
string status;
将获得整行输入,然后您可以检查行内的字符。
答案 1 :(得分:0)
您可以使用getchar()
保存到状态,
它只从缓冲区中读取一个字符..
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);
}