Question

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

Was it helpful?

Solution

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

OTHER TIPS

You check if the input was successful:

if (cin >> num)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top