c++ - 循环重复次数超过应有次数的问题

标签 c++

#include <iostream>
#include <cmath>
#include <string>

using namespace std;

int main()
{
    char terminate;
    double a, b, answer;
    char operators;

    cout << "Please enter your expression: ";
    terminate = cin.peek();
    cin >> a >> operators >> b;

    while (terminate != 'q')
    {
        switch(operators)
        {
            case '+':
                answer = a + b;
                break;
            case '-':
                answer = a - b;
                break;
            case '*':
                answer = a * b;
                break;
            case '/':
                answer = a / b;
                break;
            case '^':
                answer = pow(a,b);
                break;
        }

        cout << a << " " << operators << " " << b << " = " << answer << endl;

        cout << "Please enter your expression: ";
        cin.clear();
        terminate = cin.peek();
        cin >> a >> operators >> b;
    }

    return 0;
}

这是我的简单计算器程序,它会重复并要求用户输入二进制表达式,直到输入值“q”,但是在输入“q”时,while 循环仍然会再次执行一次,即使变量terminate 的值为“q”。我不明白为什么要这样做,我们将不胜感激。谢谢

最佳答案

让我们看一下这个输入发生了什么的例子:

1 + 1 回车

terminate = cin.peek();

这一行将查看缓冲区,读取其中的内容,但不会将其从缓冲区中删除

cin >> a >> operators >> b;

这一行会读取1 + 1 并存储在a operators b 并从缓冲区中删除这些字符

现在您剩下的是仍在缓冲区中的 Enter 键,下次您尝试读取缓冲区时将读取它,这就是您下次发出的地方你调用 terminate = cin.peek(); 你得到的是 \n 而不是你期望的 q

我注意到您可能已尝试通过调用 std::cin::clear 来解决该问题,但这不是该函数的作用。该函数会重置 iostate 标志,而这不是您要查找的内容。如果你想清除缓冲区,那么你必须调用 std::cin::ignore

关于c++ - 循环重复次数超过应有次数的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22998357/

相关文章:

c++ - Armadillo ,在每一列中找到最大索引

c++ - 潜在狄利克雷分配 (LDA) 实现

c++ - 使用删除删除std vector 的元素对象: a) memory handling and b) better way?

c++ - 从 C++ 文件中读取后,如何将常规字符串数组转换为 const 字符串数组?

c++ - 无法在代码块中使用图形编程

c++ - 为什么 OpenCL 内核不对 Image2D 使用正常的 x y 坐标?

c++ - 如何为 native 单元测试添加额外的 dll 搜索目录?

c# - LoadLibraryW 调用在 IIS 上挂起

c++ - 从派生范围调用函数

c++ - 使用指向字符的指针打印字符数组。