#include "stdafx.h"
#include <iostream>
#include <stdexcept>
using namespace std;
inline double multplication(double num1, double num2);
inline double division(double num1, double num2);
inline double addition(double num1, double num2);
inline double substraction(double num1, double num2);
int main()
{
cout << "Welcome to 'The calculator' just enter a number the operator '*, /, + and -' then the second number enjoy" << endl;
char redo = 'r'; double result = 0; int cnt = 0;
while (redo == 'r' || redo == 'R')
{
try
{
if (cnt > 0)
cout << "Ok same rules as before" << endl;
int num1 = 0, num2 = 0; char inputedOperator = '*';
cin >> num1 >> inputedOperator >> num2;
switch (inputedOperator)
{
case('*') :
result = multplication(num1, num2);
break;
case('/') :
result = division(num1, num2);
break;
case('+') :
result = addition(num1, num2);
break;
case('-') :
result = substraction(num1, num2);
break;
default:
throw runtime_error("Invalid operator");
}
}
catch (runtime_error err)
{
cout << err.what() << endl;
cout << "Enter y to redo or anykey to exit" << endl;
cin >> redo;
++cnt;
continue;
}
cout << "The answer is " << result << "\nPlease enter y to redo or anykey to exit" << endl;
cin >> redo;
++cnt;
}
cout << "Thanks for using" << endl;
return 0;
}
inline double multplication(double num1, double num2)
{
return num1 * num2;
}
inline double division(double num1, double num2)
{
return num1 / num2;
}
inline double addition(double num1, double num2)
{
return num1 + num2;
}
inline double substraction(double num1, double num2)
{
return num1 - num2;
}
每当我跑步时,3 * 2&#39;作为输入,它工作正常,但对于&#39; 3 * d&#39;它会在我的代码结尾处循环,并且#3; 3 d 3&#39;很好,因为它只是sais无效的运算符。所以我的问题是为什么它会继续循环以及如何解决它?
答案 0 :(得分:0)
加入
if (cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<int>::max(), '\n');
}
清除无效输入和缓冲区。在cplusplus.com/forum/beginner/2957 /
上找到了相关信息