Hello all,

I did this program below, it is meant to get a student name then 5 of his/her grades sums them up in a void function and calculate the average but outputs the average from the main

the problem is that the loop goes on and prints the prompt but takes no input

how can I fix that ?

``````# include <iostream>
# include <string>
using namespace std;

int main()
{
char name;
double average;

cout << "Student name" <<endl;
cin.get(name);
cout <<endl;

cout << "The average is " << average <<endl;

return 0;
}

{
double sum=0;
double average;

for (int i=0; i<5; i++)
{
average = sum/5;
}
}``````

## All 5 Replies

``````# include <iostream>
# include <string>

using namespace std;

double average;
int main()
{
char name;

cout << "Student name" <<endl;
cin.get(name);
cout <<endl;
cout << "The average is " << average <<endl;
return 0;
}
{
double sum=0;

for (int i=0; i<5; i++)
{
average = sum/5;
}
}``````

Actually, take the final average calculation (average = sum/5) _outside_ of the for loop otherwise you'll be calculating it each time.

it still does not work

Does your function have to be void? If not change it to double and do `return average;` To fix it as is:

``````cin.ignore();
for (int i=0; i<5; i++)
{

}
average = sum/5;``````

Your name input was mucking up the input stream.

``````# include <iostream>
# include <string>
using namespace std;

// Protype for the avg function:
// Passing by reference mainAverage which is the average variable declared in
// main the function can have a void return type and still get the average grade
// back into the main function because the value of mainAverage is directly changed
// in the avg().
void avg (double& average);

int main()
{
// String variable for the student's name
string name;
double mainAverage = 0;

// Gets the name of the student
cout << "Student name: ";
getline(cin, name);

// sends mainAverage into the avg()
avg(mainAverage);

cout << "The average grade for " << name << " is " << mainAverage << "."<<endl;

system("PAUSE");
return 0;
}

void avg (double& average)
{
double sum = 0;

// Extra space to make it look better
cout << endl;

// Loops through 5 times gathering a grade value and summing them all together
for (int i=0; i<5; i++)
{
}
cout << endl;

// Caclulates the average after the loop is complete
average = sum / 5;
}``````

You had a few problems so here is a short list of them:
1) Your name variable was declared as a single char and not a string. This is why if you gave a student name of anything more than 1 character you it would just flash the grade prompt but not take any input, because it is an error to try to put more than 1 character in a single character variable.