Hi! I'm very new to C++ and have two questions whose answers are probably comically obvious. Any suggestions you have will be accepted gratefully.
I'm writing a program that calculates the average of integers (grades) input by the user. Once the average is computed, the program should ask if the user wants to find the average of another set (start over again).
1. How do I use cin.clear() to prevent incorrect input types from causing infinite loops? I know it has to do with cin.clear() and cin.ignore(), but I'm not sure where to put them.
2. How do I reset the sum variable to 0 if the user wants to input another set of integers to be averaged? As it is now, when the user wants to input another set of numbers, the program is automatically including additional, unwanted integers in the set of numbers to be averaged.
#include <iostream> // Allows the user to input data and view output
using namespace std; // Allows us to use the standard C++ library
int main() {
int stillentering = 1; // Whether or not the user is still entering grades to be averaged
int grade; // Grade input by user
int sum = 0; // Summation of grades
int gradecount = 0; // Number of grades
char moregrades; // Whether or not the user is still entering grades to be averaged
float average;
int playagain; // Whether or not the user wants to compute another set of averages
do
{
do
{
do
{
cout << "Please enter a number from 0 to 100." << endl; // Prompts the user to enter a grade
cin >> grade; // Stores the input as variable "grade"
cin.clear();
cin.ignore(1000,'\n');
} while ( !( grade <= 100 ) || !( grade >= 0 ) );
if ( grade <= 100 && grade >= 0 )
{
sum = sum + grade;
gradecount++;
cout << "Would you like to input another grade? (y/n)" << endl;
do
{
cout << "Please type y if you would like to input another grade,\nor type n if you are done entering grades." << endl;
cin >> moregrades;
} while ( ( moregrades != 'y' ) && ( moregrades != 'n' ) && ( moregrades != 'Y' ) && ( moregrades != 'N' ) );
if ( ( moregrades == 'y' ) || ( moregrades == 'Y' ) )
{
stillentering = 1;
cout << "You are still entering grades." << endl;
}
if ( ( moregrades == 'n' ) || ( moregrades == 'N' ) )
{
stillentering = 0;
cout << "You are done entering grades." << endl;
}
}
} while ( stillentering == 1 );
average = (float)sum / gradecount; // calculate the average
cout << "The average of these numbers is " << average << "." << endl;;// output the average
cout << "Would you like to compute the average for another set of numbers? Type 1 for yes, 0 for no." << endl;
cin >> playagain;
cin.clear();
sum = 0;
cout << "sum should be 0" << endl;
} while ( playagain == 1);
return 0;}