Restrict user to input real number only in C++

前端 未结 10 2066
旧时难觅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: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  // 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 !

提交回复
热议问题