Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C++

Handling Input to Avoid Program Crashes

5.00/5 (1 vote)
15 Jun 2010CPOL 4.5K  
Instead of doing what the original author does (which is read a string and convert it manually into a number) why not use streams properly?When a program wants a number, read a number and then check the stream state is still good. If it's not you know the user has entered something that's...
Instead of doing what the original author does (which is read a string and convert it manually into a number) why not use streams properly?

When a program wants a number, read a number and then check the stream state is still good. If it's not you know the user has entered something that's not a number. If the stream's in an error state you can clear the error, bin the rest of the input and ask them to start again...

#include <iostream>
#include <string>

int main()
try
{
    while( std::cin )
    {
        std::cout << "I convert temperatures from centigrade to fahrenheit\n"
                     "Please enter a temperature in centigrade for me"
                     " to convert(CTRL+Z to exit): ";

        double centigrade = 0.0;
        std::cin >> centigrade;
        if( std::cin.good() )
        {
            std::cout << "You entered " << centigrade << "C\n"
                      << "That's equivalent to "
                      << centigrade * 9.0 / 5.0  + 32 << "F" << std::endl;
        }
        else if( !std::cin.eof() )
        {
            std::cout << "You're such a kidder!" << std::endl;
            std::cin.clear();
            std::string junk;
            std::getline( std::cin, junk );
        }
    }
}
catch( std::exception &e )
{
    std::cout << "Something went wrong: " << e.what() << std::endl;
}
catch( ... )
{
    std::cout << "Something went wrong, no idea what!" << std::endl;
}


While it's still possible to stuff up the input to the program you won't get anything that causes it to crash. (Please treat this assertion as a challenge and if you manage it I can improve the code).

Oh, and if you're on Linux/UNIX you want to press CTRL+D to exit the program.

Cheers,

Ash

PS: Edited to add the include directives, the compiler considers it a bit rude to leave them out.

PPS: Edited again so the angle brackets showed up... grrr...

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)