Christian Whitehead
Christian Whitehead

Reputation: 1

Trying to pass a vector of a struct type but no console output

I am reading a file and storing the data in a vector of a struct type. I have 3 different functions:

  1. readFile(insert arg here) // reads a text file and gets a name and hours worked throughout the week.
  2. bubbleSort(`more arg') // self-explanatory
  3. output(`arg') // outputs contents of said vector

Function prototypes:

void readFile(vector<Employee *> workers, int numOfEmployees);
void bubbleSort(vector<Employee *> workers, int numOfEmployees);
void output(vector<Employee *> workers, int numOfEmployees);

Struct:

struct Employee
{
    string name;
    vector<int> hours;
    int totalHours;
}

Main:

vector<Employee *> workers;
int numOfEmployees = 0;

readFile(workers, numOfEmployees);
bubbleSort(workers, numOfEmployees);
output(workers, numOfEmployees);
cout << endl;

system("pause");
return 0;

readFile:

ifstream fin;
fin.open("empdata4.txt");
if (fin.fail())
{
    cout << "File failed to open.  Program will now exit.\n";
    exit(1);
}

fin >> numOfEmployees;
workers.resize(numOfEmployees);

for (int row = 0; row < numOfEmployees; row++)
{
    workers[row] = new Employee;
    workers[row]->hours.resize(7);

    fin >> workers[row]->name;

    for (int i = 0; i < 7; i++)
    {
        fin >> workers[row]->hours[i];
    }
}

// excluding bubble sort for obvious reasons

output:

 for (int i = 0; i < numOfEmployees; i++)
 {
     cout << workers[i]->name << " ";
     for (int x = 0; x < 7; x++)
     {
         cout << workers[i]->hours[x] << " ";
     }
     cout << endl;
 }

The console output is blank, minus the cout << endl; in main and system("pause"); I think I set everything up correctly for the most part, but I still don't know. Thanks for any help!

EDIT: Added function prototypes and struct

Upvotes: 0

Views: 62

Answers (1)

lamandy
lamandy

Reputation: 982

Change your function headers to

void readFile(vector<Employee *>& workers, int& numOfEmployees);
void bubbleSort(vector<Employee *>& workers, int& numOfEmployees);
void output(vector<Employee *>& workers, int& numOfEmployees);

Without the reference &, you are passing by value, thus whatever modification you did to the vector and int inside your function will not affect your vector and int in your main and thus your vector in main is always empty.

Even better, don't even need numOfEmployees.

void readFile(vector<Employee *>& workers);
void bubbleSort(vector<Employee *>& workers);
void output(vector<Employee *>& workers);

If you need the number of employees, just call workers.size()

Upvotes: 1

Related Questions