I know this question has been asked before, but the answers have not solved my problem thus I ask this question
I have a simple program to find the greatest of three numbers which should accept only floating numbers. In case a character or string is entered an error needs to be displayed and the user needs to enter again.
I have a function to take a valid floating input
float validInput()
{
float x;
cout<< flush;
cin >> x;
while(cin.fail())
{
cin.clear();
cin.ignore(numeric_limits<streamsize>::max(),'\n');
cout << "Not a numeric value please enter again\n";
cin >> x;
}
return x;
}
so I take input in the main function using validInput like
int main()
{
float x = validInput();
float y = validInput();
float z = validInput();
findGreatest(x,y,z);
return 0;
}
This method works for most inputs. It fails when I enter a number followed by a character the validInput function fails weirdly. On giving such an input it displays the error message "Not a numeric value please enter again" but does not take another input instead it considers the numeric value before the characters as the input and stores it. My requirement is to ignore the entire input and ask for a fresh input
From my understanding
cin.ignore(numeric_limits<streamsize>::max(),'\n');
does not ignore the numbers that are entered in the beginning of the input but only clears out the characters from the stream even though cin.fail() was true.
Is there any way to fix this? it probably needs different parameters for cin.ignore not sure though.
Thanks in advance
sources: https://stackoverflow.com/a/16934374/5236575
PS: I can't use any special libraries like boost. The code is for implementing test cases for software testing so it needs to handle any type of input correctly.