Restrict user to input real number only in C++

前端 未结 10 1919
旧时难觅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:15

    I would recommend using this option:

    • Firstly, do #include <conio.h>.
    • While true:
    • Store getch() in a character variable (Will not be displayed on screen).
    • Validate the character variable in the previous step.
    • If there are any errors, do nothing.
    • Else if the character variable is '\r' ('\r\n' normally), break out of the loop.
    • Else, output it on the screen.
    0 讨论(0)
  • 2021-01-15 07:22

    Unfortunately you cannot avoid it... You can accept a string as input and parse the string (maybe with regex) for correctness.

    0 讨论(0)
  • 2021-01-15 07:25

    You can retrieve your data as a std::string then use one of the standard string conversion function to see if the content matches your expectations.

    0 讨论(0)
  • 2021-01-15 07:27

    Check out the sscanf function.

    0 讨论(0)
提交回复
热议问题