-
Loop skip problem
Hi guys
I am having a problem with a peice of code. The program compiles ok ( I do get a warning about a mis-match '<' type in the for loop ).
Basically, I am trying to read in 10 scores per student, calculate the average and pass it to a vector. Now, this all seems to be working fine, but when I have read in the final grade for the first student, it terminates with no reason ( I get no seg-fault error so it isnt that ) and doesnt go to the next student.
Here is my code
Code:
// function to input 10 test scores and calculate
// the average of the scores per student
void GradeBook::inputGrades( const std::vector<std::string> &rStuNm )
{
int counter = 1;
int totalScore = 0;
int result = 0;
double average = 0;
// read in 10 scores per student
for ( int i = 0; i < rStuNm.size(); )
{
while ( counter <= 10 )
{
std::cout << "Enter grade[ " << counter << " ] for student "
<< rStuNm[ i ] << " : ";
std::cin >> result;
totalScore += result;
counter++;
}
// calculate the average for this student
average = totalScore / counter;
// place claculated average in vector
m_AverageOfResults.push_back ( average );
// goto the next student
i++; // THIS IS NOT BEING READ?
}
}
Oh, and the constructor is:
Code:
GradeBook::GradeBook ( std::string name ) :
m_Students ( m_MAX_VECTOR, "" ),
m_AverageOfResults ( m_MAX_VECTOR, 0 ),
m_LetterGrade ( m_MAX_VECTOR, '\0' ),
m_CourseTaken ( m_MAX_VECTOR, "" ) ...
In case the helps. MAX_VECTOR has a value of 10 btw :)
Any help appreiciatred. It looks like somthing very simple I am doing wrong.
-
You are going over the limit of your vector:
Code:
while ( counter <= 10 )
will allow the loop to continue until counter == 11, which causes the vector to overrun.
I would also like to change your multiple vectors: Why not have a single vector of
Code:
struct GradeRecord
{
std::string name;
double AverageOfResults;
char LetterGrade;
std::string CourseTaken;
}
--
Mats
-
Why are you incrementing the loop counter in the body of the loop?
-
And medievalelks comments made me look again on the code - you won't ever read the second students grades. You may want to use a traditional for-loop for that too.
--
Mats