Handling Input to Avoid Program CrashesThis program will help you understand how you can avoid crashes for unexpected input.
IntroductionThis article is about validating input in order to avoid crashing when invalid input is given by the user. BackgroundEveryone has had, at one point of time, experienced a crash due to incorrect input. This is an example of one way it could be handled in C++. Using the CodeYou can create a project using the attached CPP code. Compile the application and try to enter string where number is required. The program will complain instead of crashing. Just play around with it.
/*
Developed by : Dhruvkumar Rangunwala
Posted 14 Jun '10 6:55 AM
dhruv_mca117
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> 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... This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)
| |||||||||||||||||||||||||||||