Restrict user to input real number only in C++

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

    You cannot restrict what user types on the keyboard. You can accept it as std::string and use boost::lexical_cast to convert it to your expected number type and catch and process boost::bad_lexical_cast exception.

    0 讨论(0)
  • 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.

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

    Here's some pseudo code;

    double num;
    
    while( num != realNum)   //check input is valid
    {
        cin >> num;
    }
    ....
    
    0 讨论(0)
  • 2021-01-15 07:08
    double number
    if (cin >> number) {
        do_stuff_with(number);
    } else {
        std::cerr << "That wasn't a number!";
    }
    
    0 讨论(0)
  • 2021-01-15 07:10

    I always use this code to request a specific type of input(Except strings and chars). The idea is to request any numeric type and use stringstream to see if it can be stored as the requested type, if not it will keep prompting the user until he inputs the requested type.

    template <typename T> // will not work with strings or chars
    T forceInputType_T() {
     T name;
     bool check = false;
     string temp;
     while (check == false) {
        cin >> temp;
        stringstream stream(temp);
        if (stream >> number) {
            check = true;
        } else {
        cout << "Invalid input type, try again..." << endl;
        }
    }
    return name;
    

    }

    If you want to use a Boolean then you could check every character in the string if it contains a number than return false and keep asking for an valid input with a loop !

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

    You can use regex to solve it

    double inputNumber()
    {
        string str;
        regex regex_double("-?[0-9]+.?[0-9]+");
        do
        {
            cout << "Input a positive number: ";
            cin >> str;
        }while(!regex_match(str,regex_double));
    
        return stod(str);
    }
    

    Remember that include regex library in the header.

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