cin input validation returns wrong

I have this function that is supposed to take a float as a parameter and then call the getLine() method to accept the users input. The function basically just checks to see if what the user input was of the same data type, if it is it returns the input value, if not then it keeps looping through taking new input until its correct. The problem is no matter what number you put in the output always returns as 140734799803512
Does anyone see where this is going wrong?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
float InputValidation(){
    float num;
    string strInput;
    while (true){
        getline(cin, strInput);
        
        // Converts from string to number. Prevents the user from entering in a string which causes the program to go into an infinite loop.
        stringstream myStream(strInput);
        if ( (myStream >> num) )
            break;
        cout << "ERROR: Invalid input.\nPlease try again: " << endl;
    }
    return num;
}


You also need to include <string> and <sstream>.
I see no error there. Is this really the exact code you are using?

(If it is, there is something wrong with your compiler, because the side effect on num must be completed before breaking.)

There is, BTW, another issue. The user can input "123abc" and it will return as an okay input. If that is not okay, check out:

http://www.cplusplus.com/forum/beginner/13044/#msg62827

(The stuff on lines 33-40 is what is important.)
Line 9 only checks if the first part of the stream is a number you probably want to check if the first part of the stream is a number and the only thing in the stream.

The reason you get that arbitrary number is because you don't initialize num on line 2 and it probably is not reading in correctly on line 9. Just realized that the only way to leave the while is with that if statement so that shouldn't be the case
Last edited on
I think it was just xcode acting up, I quit the program and reopened it and it worked fine! Thanks for all the help though!
Topic archived. No new replies allowed.