为什么这个循环在输入数字时执行了 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);
}
最佳答案
您的变量 status
可能声明为:
char status;
因此,cin >> status
从输入中读取一个单个 字符。但是,您可能键入了多个,因为输入被缓冲并且您需要按 Enter 键。
相反,使用这个声明:
string status;
这将获取整行输入,然后您可以检查该行内的字符。
关于c++ - 输入数字时出现循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7603868/