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/