c++ - 输入数字时出现循环错误

标签 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);
    }

最佳答案

您的变量 status 可能声明为:

char status;

因此,cin >> status 从输入中读取一个单个 字符。但是,您可能键入了多个,因为输入被缓冲并且您​​需要按 Enter 键。

相反,使用这个声明:

string status;

这将获取整行输入,然后您可以检查该行内的字符。

关于c++ - 输入数字时出现循环错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7603868/

相关文章:

c++ - BigInteger:在 C++ 中使用 ofstream 写入文件时将基数更改为 2 的方法?

c++ - 在 float 不好的样式上使用增量(运算符++)吗?

c++ - rand() 总是在应用程序重启时返回相同的序列

c++列表类作为学生类型

c++ - 如何通过跳过=从txt文件中读取整数?

c++ - 向继承自 QGraphicsScene 的类添加信号

c++ - 动态可调阵列和 OpenMP

C++ Borland Builder 表单 - 调用函数

c++ - 修复删除 #include windows.h 和相关函数调用后的编译器错误

c++ - 尝试创建一个对象并将其打印到输出