如果在条件下如何区分零和未定义?

时间:2014-01-12 07:36:48

标签: c++ undefined zero

    int todayPrice
cout << "Enter the price of the item this year:\n";
                cin >> todayPrice;
    if ( todayPrice == 0 ) {
            throw DIVIDED_BY_ZERO;
        } else if ( todayPrice < 0 ) {
            throw LESS_THAN_ZERO;
        } else if ( !todayPrice ) {
            throw NOT_A_NUM;
        }

如果用户输入零或字符串(我猜测它将是未定义的),它将评估为“number == 0”,并且它们都抛出DIVIDED_BY_ZERO异常。

如何区分todayPrice未定义(当用户输入字符串时)但不是0 ??

2 个答案:

答案 0 :(得分:3)

如果用户输入除整数之外的任何内容,则输入流将进入失败状态,您可以使用该流检查:

if (std::cin >> todayPrice)
{
    // Do your other checks
}
else
{
    // User entered something that wasn't a valid integer
    std::cout << "Not a valid integer input\n";
}

答案 1 :(得分:1)

您检查输入是否成功:

if (cin >> num)