Input validation and sanity checking.

Is there a better way to do input type validation / sanity checking? Here is what I have so far:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
    double cost = NULL;
    string buffer = "";
    regex check_positive_number ("^([.]\\d+|\\d+([.]\\d+)?)$"); // checks if input is a positive number.

    while (true) {
        cout << "Please enter an amount: ";
        cin >> buffer;
        if (regex_match (buffer, check_positive_number)) {
            cost = stod (buffer);
            break;
        }
        else {
            cout << "Error: Input must be a positive number and must not include a dollar sign or any other symbols, except for a decimal point. Example: 9.87" << endl;
        }
    }
Last edited on
just try to read and fail.
you may use an auxiliar stringstream and check for remaining characters
1
2
3
4
std::cin>>buffer;
std::istringstream input(buffer);
if(input>>cost and input.peek()==EOF)
   //successs 


PS: to avoid backslash hell R"(a raw string literal, here \ means \)"
Last edited on
Topic archived. No new replies allowed.