-1

I am trying to use a while loop to calculate the average of 3 inputted grades, but I can not enter the next grade as the loops keep on going without giving me the chance to enter the next grade.

#include<iostream>
using namespace std;

int main()
{
    int grade = 0;
    int count = 0;
    int total = 0;

    cout << "Enter grade: ";
    cin >> grade;
    
    while (grade != -1)
    {
        total = total + grade;
        count = count + 1;

        cout << "Enter next grade: ";
        cin >> grade;

    }
    int(average) = total / 3;
    cout << "Average: " << int(average) << endl;

    system("pause");

}
Sunderam Dubey
  • 1
  • 11
  • 20
  • 40

1 Answers1

0

I tested your code with integer and it works fine.

If you only take int as input, the best is to put something to check the input type. Use cin.fail() to check if user input anything other than int.

for example:

while(cin.fail()) {
    cout << "Error" << endl;
    cin.clear();
    cin.ignore(256,'\n');
    cout << "Please enter grade:"
    std::cin >> grade;
}

which I refer from https://www.codegrepper.com/code-examples/cpp/how+to+check+type+of+input+cin+c%2B%2B

and here as well Checking cin input stream produces an integer

Allenchew
  • 23
  • 1
  • 3