如果为char分配了非char则为无限循环

问题描述 投票:1回答:1

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

首先输入运算符,然后输入两个数字。

问题是,例如,如果我输入"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();
    }
}
c++ c++14 cin
1个回答
0
投票

问题是字符串的其余部分将分配给num1p将被Oper占用,lus将被分配给num1,这将失败,failbit标志将被设置,您将进入无限循环。

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

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; //...
© www.soinside.com 2019 - 2024. All rights reserved.