如果char被指定为非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:

活样本

#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 inputn";
cin.clear();          //reset failbit
cin.ignore(numeric_limits<streamsize>::max(), 'n'); //ignore everything till newline
return;
}
if (Oper == '+')
cout << num1 + num2 << endl;
//...

旁注:

  • 您应该有一个停止条件,让用户离开程序
  • 为什么";使用命名空间std"被认为是不好的做法

最新更新