如何在 if 条件中区分零和未定义

How to distinguish zero from undefined in if condition?

本文关键字:未定义 中区 条件 if      更新时间:2023-10-16
    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;
        }

如果用户输入零或字符串(我猜是未定义的),它将计算为"数字 == 0",并且它们都抛出DIVIDED_BY_ZERO异常。

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

如果用户输入的不是整数,则输入流将进入失败状态,您可以通过流进行检查:

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

检查输入是否成功:

if (cin >> num)