c++ - 为什么这个 while 循环在输入的每个字符之后重复?

标签 c++ function loops while-loop

我编写了一些代码,使用 while 循环检查用户是否输入了正确的输入类型。问题是在您输入每个错误的字符后,它会再次重新循环。

但是当您输入多个字符时,它会一次又一次地循环相同的 cout 语句。例如,如果我输入“qwerty”,它会输出那些 cout` 语句 6 次,而我只希望它运行一次。

代码如下:

#include <iostream>
using namespace std;
int main(){
    // Declare the variables
    int choice = 0;
    bool valid = false;

    while(!valid){

    valid = true;
    //Ask the user for their choice
    cout << "Which function would you like to use? \n";
    cout << "1) Average Function \n";
    cout << "2) Mean Absolute Deviation Function \n";
    cout << "3) Number Sorting Function \n";
    cout << "4) Median Function \n";
    cout << "5) All of the above \n";
    cout << "6) Calculator Function \n";
    cout << "Your choice: ";
    cin >> choice;

        if(cin.fail() || choice > 6 || choice < 1){
            cout << "ERROR, PLEASE ENTER ONLY VALID SYMBOLS \n";
            cout << "--------------------- \n";
            valid = false;
            cin.clear();
            cin.ignore();
        }

    }
}

最佳答案

循环发生是因为您的 cin 中还剩下字符提取一个后缓冲。所以如果你输入 querty<enter> , 在它处理 q 之后它仍然有 uerty\n处理。然后它循环,因为它没有找到满足您条件的输入值 choice > 6 || choice < 1并尝试其他字符提取。它能够执行此操作 6 次,直到缓冲区为空且 cin.fail()标志已设置。

另一种方法是将整行作为字符串读取并从该行中提取一个整数。

#include <iostream>
#include <sstream>
#include <string>
using namespace std;

int displayUserInstructions(){

    string line;

    while(true){

        cout << "Which function would you like to use? \n";
        cout << "1) Average Function \n";
        cout << "2) Mean Absolute Deviation Function \n";
        cout << "3) Number Sorting Function \n";
        cout << "4) Median Function \n";
        cout << "5) All of the above \n";
        cout << "6) Calculator Function \n";
        cout << "Your choice: ";

        if(getline(cin, line)){

            stringstream ss(line);
            int choice;

            if(ss >> choice && (choice >= 1 && choice <= 6)){

                return choice;
            }

            cout << "ERROR, PLEASE ENTER ONLY VALID SYMBOLS \n";
            cout << "--------------------- \n";
        }
    }
}

int main()
{
    int choice = displayUserInstructions();
    cout << "You made the valid choice of " << choice << '\n';
}

关于c++ - 为什么这个 while 循环在输入的每个字符之后重复?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42127358/

相关文章:

c - 打印强数(c编程)

java - 将变量值从循环内部传递到外部

c++ - 如何将QImage转换为opencv Mat

c++ - 在结构定义中使用守卫宏是什么意思

c++ - 为什么 Alexandrescu 不能使用 std::uncaught_exception() 在 ScopeGuard11 中实现 SCOPE_FAIL?

c++ - 这个程序不是要求数组中预先确定的 5 个数字吗?

c++ - 如何避免对非构造函数进行隐式转换?

c - C 中未定义对 'function' 错误的引用

javascript - 更新函数 JQuery 内的变量

MySQL - 用户在初始订阅购买的前 6 个月内的每月支出