0

我有这个程序:

#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 不是整数!

4

1 回答 1

0

调用后cin,检查:

if (!cin)
{
    cout << "Not an integer!" << endl;
}

或者,cin当输入不匹配时设置称为故障位的东西。你可以用cin.fail()

于 2013-07-07T13:44:31.857 回答