| mcoliver88 (57) | |
|
Hi All I am writting a menu, where a user will use a number to choose their option. How do i stop the user from entering a char, or check to make sure that it is an int. I have tried using isdigit and isalpha and noting is working Thanks Michael | |
|
|
|
| Darkmaster (311) | |
| use the ascii table | |
|
|
|
| JLBorges (1335) | |||
|
> How do i stop the user from entering a char You can't; the user can enter anything. In your program you need to check what the user has entered, and if it is something invalid, throw it away and seek another input from the user. For instance:
| |||
|
|
|||
| mcoliver88 (57) | |
|
Thank you for your reply. I am trying to run this code in my program and on its own, i get a fatal error message, due to unresolved externals. Thanks Michael | |
|
|
|
| JLBorges (1335) | |||
|
> I am trying to run this code in my program and on its own, > i get a fatal error message, due to unresolved externals. At the very least, you need a main() Try this:
| |||
|
|
|||
| mcoliver88 (57) | |
| This is fantastic so much, as i am a newbie at C++ could you explain your code, so i can understand it better | |
|
|
|
| JLBorges (1335) | |
Do you know what a function is? int read_int( int lower_bound, int upper_bound ) is a function.
| |
|
|
|
| mcoliver88 (57) | |
|
i know what a function is, but i wasnt sure of the std:cerr, std::cin.clear, i have never come across these before | |
|
|
|
| JLBorges (1335) | |
|
> i wasnt sure of the std:cerr http://en.wikipedia.org/wiki/Standard_streams#Standard_error_.28stderr.29 > std::cin.clear if( std::cin >> value ) // if the user has entered a number essentially tests if the stream is in a good state after the attempt to read an integer. std::cin is put into a failed state - the failbit is set - if the expected data was not successfully read. This would be the case if we tried to read an integer and the user typed in - the input buffer contains - "abc\n".Once an error state is set, it remains set; and any operation on the stream would fail if it is not in a good state. So we need to put std::cin back into a good state before we do anything else with it. That is what std::cin.clear() does.http://www.cplusplus.com/reference/ios/ios/clear/ After the error state is cleared, we also need to extract and throw away the incorrect characters remaining in the input buffer ("abc" in the previous example). That is what std::cin.ignore( 1024, '\n' ) ; // and discard cruft in the input buffer http://www.cplusplus.com/reference/istream/istream/ignore/ does. | |
|
|
|
| PalashBansal96 (2) | |||
You can just input a char and check if it is a digit or not.
| |||
|
|
|||