문제

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

If a user enters a zero or a string(which will be undefined I guess), it will evaluates to "number == 0", and they both throw DIVIDED_BY_ZERO exception.

How can I distinguish that the todayPrice is undefined(when a user enters a string) but not 0??

도움이 되었습니까?

해결책

If the users enters anything but an integer, then the input stream will enter a failed state, which you can check with the stream:

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

다른 팁

You check if the input was successful:

if (cin >> num)
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top