我有一个执行基本算术操作的程序。
首先输入运算符,然后输入两个数字。
问题是,例如,如果我输入"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();
}
}
问题是字符串的其余部分将分配给num1
,p
将被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;
//...