如何检测错误的数据类型?

时间:2013-07-07 13:39:55

标签: c++ types

我有这个程序:

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

1 个答案:

答案 0 :(得分:0)

致电cin后,请检查:

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

或者,cin在输入不匹配时设置称为failbit的内容。您可以使用cin.fail()

进行测试