Restrict user to input real number only in C++

前端 未结 10 1917
旧时难觅i
旧时难觅i 2021-01-15 06:40

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

10条回答
  •  被撕碎了的回忆
    2021-01-15 07:05

    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:

    1. Use getline to read a line
    2. Parse and understand the line
    3. If line is invalid, give error to user and go to 1

    This is alright and quite common. It uses dynamic memory though. Another option would be:

    1. Use cin >> value; like you normally do
    2. Check cin.fail() to see if input was correctly read (check for cin.eof() also)
    3. 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.

提交回复
热议问题