For Eg. Accept 4.55324 as the user input and reject if 6.22356 is entered, i.e accept till 5 decimal places.
-
5Read as a string, and count the number of characters after the decimal point (which might be different in different locales)?Some programmer dude– Some programmer dude2014-09-23 05:47:57 +00:00Commented Sep 23, 2014 at 5:47
-
Could you give more examples and motivate your question. Why that strange requirement?Basile Starynkevitch– Basile Starynkevitch2014-09-23 05:52:34 +00:00Commented Sep 23, 2014 at 5:52
-
That was the requirement of the question.. just to check conceptsSmme– Smme2014-09-23 06:08:01 +00:00Commented Sep 23, 2014 at 6:08
-
But after reading floating-point-gui.de you should understand that the requirement is useless.Basile Starynkevitch– Basile Starynkevitch2014-09-23 06:09:18 +00:00Commented Sep 23, 2014 at 6:09
2 Answers
The easiest way to do this is to read the input as a string, check that it matches you desired format, and only then convert it to a number. For example, using the C++11 regex feature for validation:
double number;
std::string input;
std::cin >> input;
std::regex pattern ("^[-+]?[0-9]+(\.[0-9]{1,5})?$");
if (std::regex_match(input, pattern)) {
number = std::stod(input);
}
else {
// handle invalid input here
}
Note that the regex above is fairly strict: it accepts 12, 012, +12.3, -12.34567 and 0.12345, but rejects 12., .5, 0.123450 and 1.2e2. You may wish to tweak it to match your specific format requirements (whatever they may be).
2 Comments
You could read a line as a string using std::getline then parse that string according to your needs (and finally convert it to a double perhaps using atof on its c_str() or preferably std::stof...)
Your examples are not precise enough: should you accept 453.210e-3 or 0.1234567e+3 etc.
You really should read http://floating-point-gui.de/ (I believe your requirements are next to useless)