1

For Eg. Accept 4.55324 as the user input and reject if 6.22356 is entered, i.e accept till 5 decimal places.

4
  • 5
    Read as a string, and count the number of characters after the decimal point (which might be different in different locales)? Commented Sep 23, 2014 at 5:47
  • Could you give more examples and motivate your question. Why that strange requirement? Commented Sep 23, 2014 at 5:52
  • That was the requirement of the question.. just to check concepts Commented Sep 23, 2014 at 6:08
  • But after reading floating-point-gui.de you should understand that the requirement is useless. Commented Sep 23, 2014 at 6:09

2 Answers 2

2

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).

Sign up to request clarification or add additional context in comments.

2 Comments

I got a thought btw What about this code.. float a; cin >> a; a=a*10000; float d = int(a)/10000.0; cout << d;
That code will, indeed, truncate a number to at most 5 decimals. (To be precise, it will usually truncate down, but it might round up for numbers like 0.1234599999999999999999, where the precision of a float is not enough to accurately represent the input.) But that's not what you asked for above.
1

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.