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;
}
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