输入数字时出现循环错误

mia*_*ech 1 c++

为什么这个循环在输入数字时执行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);
    }
Run Code Online (Sandbox Code Playgroud)

Gre*_*ill 6

您的变量status可能声明为:

char status;
Run Code Online (Sandbox Code Playgroud)

因此,从输入中cin >> status读取单个字符.但是,您可能键入了多个,因为输入已缓冲,您需要按Enter键.

相反,使用此声明:

string status;
Run Code Online (Sandbox Code Playgroud)

这将获得整行输入,然后您可以检查行内的字符.