c++ - 如何在if条件下区分零和未定义?

标签 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?

最佳答案

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

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";
}

关于c++ - 如何在if条件下区分零和未定义?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21072383/

相关文章:

c++ - 什么是冒名顶替者设计模式?

c++ - 函数void QQuickWindow::setDefaultAlphaBuffer(bool useAlpha)有什么用?

javascript - 仅当在函数内部时,循环才会返回额外的时间

javascript - 获取错误 'Cannot read property ' getAttribute' of undefined'

c++ - Qt 中的 Tab 键顺序

c++ - 转发模板自动

php - 使用带有下拉选项的 php 更新 mysql 数据

c# - 如何解析带符号的零?

Java项目返回空值

javascript - JavaScript 中的 HTML 控件数组 - 1 的复选框数组返回零长度