let say i need to get a number from user.
ex:
double x;
cout %26lt;%26lt;"enter a number \n";
cin%26gt;%26gt;x;
there is cin.fail() to check if the input in a double. however if the user enter "2343.2342dfd" then x will be store as 2343.2342 and cin.fail() is false. "dfd" is still in the string, i can use cin.ignore() to get rid of it , but mainly i want to able to detect the input error of this case.
thanks
In c++ how do i check for input error from user?
use isalpha(x) to check that x IS letters, so use (!isalpha(x)) to check that x IS NOT letters, then also use (isdigit(x)) to check that x IS digits.
what you can do is this:
double x; //declares variable x of type double
do {
cout %26lt;%26lt; "Enter a number: "; //output, input on same line
cin %26gt;%26gt; x;
} while ((isalpha(x)) || (!isdigit(x));
you can also do an if statement to check:
double x;
cout %26lt;%26lt; "Enter a number: ";
cin %26gt;%26gt; x;
if ((isalpha(x)) || (!isdigit(x))) {
cout %26lt;%26lt; "Please enter numbers only! ";
cin %26gt;%26gt; x;
}
although the if statement here only checks once, then kicks out.
Reply:check your input type as integer or double as array() having
0 to 9 if user input contain other than num then it will throw wrong input. use exception handling, i think this will work.
chelsea flower show
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment