user2331724
user2331724

Reputation: 1

Infinite Loop C++ Using Visual Studio 2012

Infinite Loop

The program below works most of the time. However, I notice that after using the loop several times, the program will go into an infinite loop instead of exiting the program when I press a key besides 1. For example I can enter 1 to enter a new score and then press any other key to exit the program till about 3 iterations. However, it tends to go into an infinite loop after the 3rd iteration instead of exiting the program when I press a key other than 1. How can I resolve this tendency to enter an infinite loop?

#include<iostream> 

using namespace std;

//Print grade for the score
void printGrade(double score)
{ 
    if (score >= 90)
        cout << 'A';
    else if (score >= 80.0)
        cout << 'B';
    else if (score >= 70)
        cout << 'C';
    else if (score >= 60)
        cout << 'D';
    else
        cout << 'F';
}

int main()
{
    int answer;

    do
    {
        cout << "Enter a score: ";
        double num;
        cin >> num;

        cout << "\nThe grade is: ";
        printGrade(num);
        cout << "\n\n";

        cout << "Do you want to enter another score (Enter 1 for Yes)? ";
        cin >> answer;
    }
    while(answer == 1);


    return 0;
}

Upvotes: 0

Views: 745

Answers (3)

Milad Qasemi
Milad Qasemi

Reputation: 3049

Use cin.ignore() before cin to make it read right

Upvotes: 0

Benjamin Lindley
Benjamin Lindley

Reputation: 103693

If cin is waiting for input of a particular type, but the user enters something which cannot be parsed as that type, cin will be put into an error state. While cin is in this error state, all future input operations with cin will fail. The user will not be prompted for input, and the input variables will never change. So answer will never change from 1.

If you enter an integer other than 1, the loop should terminate. However, if you enter something that is not an integer, that will cause an infinite loop.

To clear an error, make a call to cin.clear(), but first you need to check if there was an error, and you also need to clear the input buffer so the same thing doesn't happen again. Personally, I find the whole affair messy, and prefer to get all my user input via std::getline, which should only ever fail on stream termination. Then I use string parsing/conversion routines to check if the input matches the types I am looking for.

Upvotes: 4

Dietmar K&#252;hl
Dietmar K&#252;hl

Reputation: 153820

Always test your input after reading to see if the input was successful:

if (!(std::cin >> answer)) {
     std:cout << "failed to read input\n";
     break;
}

I guess that you stream goes into fail state an it won't do anything while std::ios_base::failbit is set. You can use std::cin.clear() to clear the state and std::cin.ignore() to ignore the next (and probably offending) character.

Upvotes: 0

Related Questions