A beginner question !
How to oblige the user to only input a number (int,float,long..) so he cannot input a char or a string when you're waiting for a number :D thanks
A beginner question !
How to oblige the user to only input a number (int,float,long..) so he cannot input a char or a string when you're waiting for a number :D thanks
There aren't any standard C/C++ libraries to prevent the user from entering a string where a number is expected.
If you are using scanf
or fscanf
, you can check the value returned from the function to make sure that you were able to read the expected number of data.
If you are using std::cin
or std::ifstream
, you use fail()
to check whether the operation succeeded or not.
In general input validation can be done in two distinct ways:
The 1st solution is easy to do, because you can check input operations for particular fields:
std::istream& is = <reference to any valid input stream>;
double value;
if(!(is >> value)) {
// Issue error message
}
The 2nd solution needs to peek for characters as they are typed in, and are immediately checked to become part of the input (and be echoed at the tty), or not. That's not possible in a simple, OS independent way.
Though there are techniques available, that enable you to restrict character inputs from std::cin
according your current parser FSM state. Check this post for more information about how this can be achieved.