How can I restrict the user to input real numbers only in C++ program?
Example:
double number; cin >> number;
and it won\'t accept t
You cannot force the user to give correct input. But you can ask them to give another input if previous was invalid. There are different procedures to do so. One is the following:
This is alright and quite common. It uses dynamic memory though. Another option would be:
cin >> value;
like you normally docin.fail()
to see if input was correctly read (check for cin.eof()
also)If failed, ignore all input until whitespace:
char c;
while (cin >> c)
if (isspace(c))
break;
This has the added advantage that in an erroneous input like this:
abc 12.14
you don't ignore the whole line, but just the abc
.