如果将 char 分配给非 char,则无限循环

Infinite loop if char gets assigned non-char

我有一个执行基本算术运算的程序。

先输入运算符,再输入运算的两个数

问题是,如果我输入,例如,"plus"或其他字符串作为Oper字符,例如:

plus 4 10

而不是

+ 4 10

它进入了一个无限循环,并且不会为新的输入重置或停止。哪里出错了?

代码如下:

#include <iostream>
using namespace std;

void calc()
{
    char Oper;
    int num1, num2;
    cout << "Enter operator and two numbers: ";
    cin >> Oper >> num1 >> num2;
    if (Oper == '+')
        cout << num1 + num2 << endl;
    else if (Oper == '/')
        cout << num1 / num2 << endl;
    else if (Oper == '*')
        cout << num1 * num2 << endl;
    else if (Oper == '-')
        cout << num1 - num2 << endl;
    else
        calc();
}

int main()
{
    while (true)
    {
        calc();
    }
}

考虑plus 4 10输入,p将被分配给Oper,然后operator >>将尝试将lus分配给以下变量,这会失败,因为他们期望 int 值,failbit 标志将被设置,您将进入无限循环,failbit 不会被重置。

为避免这种情况,您应该使用条件在输入错误的情况下重置 failbit。您可以使用 clear:

Live sample

#include <limits> //for numeric_imits and max()
//...
void calc()
{
    char Oper;
    int num1, num2;
    cout << "Enter operator and two numbers: ";
    cin >> Oper >> num1 >> num2;

    if (cin.fail()){  //condition to reset cin flags in case of a bad input
        cout << "Bad input\n";
        cin.clear();          //reset failbit
        cin.ignore(numeric_limits<streamsize>::max(), '\n'); //ignore everything till newline

        return;
    }

    if (Oper == '+')
        cout << num1 + num2 << endl;
    //...

旁注:

  • 你应该有一个停止条件让用户离开程序。
  • Why is "using namespace std;" considered bad practice?