[Solved] Array Struct Not Printing Correctly


In every function you are starting from array[-1], and in C/C++ you won’t get an exception it will just take what is in memory before the array.

Change [student-1] to [student] and initialise sum to 0.

Advice for future: don’t use ‘magic numbers’ in loops, declare them as a variable and then you can just change it in one place, less likely error prompt behaviour.

Compiled with VS 2015:

#include <iostream>
#include <fstream>
#include <cctype>
#include <cstring>
#include <iomanip>
#include <string>

using namespace std;

double calcAvg(double[][6], int);
double calcLow(double[][6], int);
double calcHigh(double[][6], int);

struct studInfo 
{
  string fname;
  string lname;
  double low;
  double high;
  double average;
} ;

int main() 
{
  ifstream input;
  ifstream input2;
  double scores[9][6];
  string firstName;
  string lastName;
  int count = 0;

  struct studInfo students[9];

  input.open("cis_testGrades.txt");

  while (!input.eof()) 
  {
    for (int a = 0; a < 9; a++) 
    {
      cout << "Student " << a + 1 << ": ";
      for (int b = 0; b < 6; b++) 
      {
        input >> scores[a][b];
        cout << scores[a][b] << " ";
      }
      cout << " " << endl;
    }
  }
  input.close();

  /*cout << calcAvg(scores, 9) << endl;
  cout << calcHigh(scores, 9) << endl;
  cout << calcLow(scores, 9) << endl;*/

  input2.open("cis_students.txt");

  while (!input2.eof()) 
  {
    input2 >> firstName;
    students[count].fname = firstName;
    //strcpy(students[count].fname, firstName);

    input2 >> lastName;
    students[count].lname = lastName;
    //strcpy(students[count].lname, lastName);

    students[count].low = calcLow(scores, count);

    students[count].high = calcHigh(scores, count);

    students[count].average = calcAvg(scores, count);

    count++;
  }

    input2.close();

  for (int a = 0; a < 9; a++)
  cout << students[a].fname << " " << students[a].lname << " " << students[a].low << " " << students[a].high << " " << students[a].average << endl;

  return 0;
}

  double calcAvg(double grades[][6], int student) 
  {
    double average;
    double sum = 0;

    for (int a = 0; a < 6; a++)
      sum += grades[student][a];

    average = sum / 6;

    return average;
  }

  double calcHigh(double grades[][6], int student) 
  {
    double high = 0;

    for (int a = 0; a < 6; a++) 
    {
      if (grades[student][a] >= high)
      high = grades[student][a];
    }
    return high;
  }

  double calcLow(double grades[][6], int student) 
  {
    double low = 100;

    for (int a = 0; a < 6; a++) 
    {
      if (grades[student][a] <= low)
      low = grades[student][a];
    }
    return low;
  }

1

solved Array Struct Not Printing Correctly