Validating Float Values

Hello everyone, I'm trying to make a program accept ONLY VALIDATE float value. However, it only accept WHOLE number instead of values which contains decimals places.

Anyone can help me solve this problem. So that I can type FLOAT values only!!
It works on integer, however I just simply changed the integer values to float values but it doesn't work at all!! Any help would be appreciated!! Thanks!!

1
2
3
4
5
6
7
8
9
10
cout << "Please enter a float number: ";
    getline(cin, inputF);
    while (!validateFloat(inputF)) {
        cin.clear();
        cout << "Invalid value please enter again!!" << endl;
        cout << "Please enter a float number: ";
        getline(cin, inputF);
    }
    convertedFloat = atof(inputF.c_str());
    cin.clear();


This is the function for validating float..

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
bool TEST::validateFloat(string input) {
    bool valid = true;
    float vf;

    if (input.length() == 0) {
        valid = false;
    } else {
//cannot have alphabet or characters
        for (int i = 0; i < input.length(); i++) {
            if (!isdigit(input[i])) {
                valid = false;
            }
        }
    }
    vf = atof(input.c_str());
//accept negative values
    if (vf < 0) {
        valid = true;
    }
    return valid;
}
1
2
3
           if (!isdigit(input[i])) {
                valid = false;
            }


You are only allowing digit characters here. Floating point values have a decimal place character which you will need to allow.

Also if you want to allow negative numbers, you should allow a '-' character. the way you are allowing negative characters is poor because it will allow input which is not valid.

IE:

-5ljksdljwoe will be treated as valid
Topic archived. No new replies allowed.