我有这个程序:
#include <iostream>
using namespace std;
int calculateResultAndPrintIt(int firstNr, char operand, int secondNr)
{
int sum = 0;
if(operand == '+')
sum = firstNr + secondNr;
else if(operand == '-')
sum = firstNr - secondNr;
else if(operand == '*')
sum = firstNr * secondNr;
else if(operand == '/')
sum = firstNr / secondNr;
else
{
cout << "Invalid operation! Returning!";
return -1;
}
cout << firstNr << " " << operand << " " << secondNr << " is " << sum << endl;
return 0;
}
int main(void)
{
int firstNr = 0;
char operand = '+';
int secondNr = 0;
cout << "Enter a value: ";
cin >> firstNr;
cout << "Enter a second value: ";
cin >> secondNr;
cout << "Enter one of the following: +, -, *, or /: ";
cin >> operand;
int back = calculateResultAndPrintIt(firstNr, operand, secondNr);
if(back != 0)
return -1;
else
return 0;
}
当它询问我“输入一个值:”或“输入第二个值:”然后我输入类似'l'的内容然后它显示如下:
输入一个数字:l 输入第二个值:输入以下值之一:+, - ,*或/:0 + 0为0
但我想要的是我可以显示消息“不是整数!”当用户输入一个角色时! 像:
输入一个数字:l 不是整数!
答案 0 :(得分:0)
致电cin
后,请检查:
if (!cin)
{
cout << "Not an integer!" << endl;
}
或者,cin
在输入不匹配时设置称为failbit的内容。您可以使用cin.fail()