Infinite Loop..

Let's say I am asking the user to enter a number of type double and they enter a char instead, why does my program go into an infinite loop? And how do I prevent this? I know it has to do something with cin.ignore()? I'm just not sure how to use it.

Thank you.
do

1
2
3
4
if(cin.fail()) //if input is bad
{
      return 0;
}
Where does that go? After cin?

Here is where I want to implement it:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
double ReadScores(int i)
{
	double score;
	cout << "Score " << i << ": ";
	cin >> score;

	while(score < 0 || score > 100)
	{
		cout << "Invalid Entry! Try again. (0.0 - 100.0)" << endl;
		cout << "Score " << i << ": ";
		cin >> score;
	}
	return score;
}


And I don't want the program to quit, I want it to output an error and ask the user to input in again.
Replace lines 4 and 5 with this:

4
5
6
7
8
9
10
    cout << "Score " << i << ": ";      // Display the prompt
    while (!(cin >> score))             // Get the input and validate it
    {
        cin.clear();                    // Clear the error flags
        cin.ignore(100, '\n');          // Remove unwanted characters from buffer
        cout << "Score " << i << ": ";  // Re-issue the prompt
    }


The above caters for non-numeric data. You could combine it with the other test,
 
    while (!(cin >> score) || (score < 0) || (score > 100)) 

etc.
Last edited on
Topic archived. No new replies allowed.