pacumming
asked on
C++ newbie - What is best way to validate input if numeric
Still working on a program and have searched the internet for various ways to test to see if input (DOS) is numeric. I see there are numerous ways and not sure how to proceed.
Values must remain as DOUBLE. Want user to have to re-input a value if they enter any non-numeric input. I guess they could enter positive and negative numbers as well as decimal. Need warning message if value is not numeric. Am using Dev C++ compiler
Thanks for the help
PC
volfunc.cpp
Values must remain as DOUBLE. Want user to have to re-input a value if they enter any non-numeric input. I guess they could enter positive and negative numbers as well as decimal. Need warning message if value is not numeric. Am using Dev C++ compiler
Thanks for the help
PC
volfunc.cpp
Here is a simple approach from:
http://stackoverflow.com/questions/784563/c-check-whether-is-number-is-int-float
Just make a readDouble function and loop until test passes.
http://stackoverflow.com/questions/784563/c-check-whether-is-number-is-int-float
Just make a readDouble function and loop until test passes.
if( !(cin >> height)) {
cout << "Bad height" << endl;
}
ASKER
Tanks,
seems to be a problem. If you enter perhaps 1111 it works fine. Great.
But it accepts 1a23 which it should not.
If you enter something invalid like a123 or something invalid, you can then never enter a valid number since it continues to cause a fail.
Can you put something in there that says input valid if it is valid? THen I will try to incorporate this into my code.
Thanks
Peter
seems to be a problem. If you enter perhaps 1111 it works fine. Great.
But it accepts 1a23 which it should not.
If you enter something invalid like a123 or something invalid, you can then never enter a valid number since it continues to cause a fail.
Can you put something in there that says input valid if it is valid? THen I will try to incorporate this into my code.
Thanks
Peter
1a23 will give 1.0 for the first double, and then fail for the 2nd double. If you want a whitespace to be the token delimiter, then cin >> string, and then check to see if the string contains the right format for a floating point number.
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
I didn't mean cin >> string literally; I meant cin >> stringName.
I thought you wanted an input of 1a23 to fail. It does not fail, but at least it throws away the a23. If you start to prompt for more than one double, then you will need to adjust.
ASKER
I actually do want 1a23 to fail and it still does not. Only numeric +- and decimal should pass.
I opened up another question for you
Thanks
PC
I opened up another question for you
Thanks
PC
Open in new window