Search code examples
c++arraysfileobjectfstream

Trying to read from a text file to an object array


so guys i have to create 5 job objects from the information from a text file which looks like this

A 0 3

B 2 6

C 4 4

D 6 5

E 8 2

the left column is its name, the next is arrival time, and the final one is the duration this is what i have right now

#include <iostream>
#include <fstream>
#include "Job.hpp"
using namespace std;

int main(int argc, const char * argv[]) {

  string fileinfo;
  string programname;


//gets Jobs.txt from commandline
programname.append(argv[1]);



Job jobs[5];
fstream afile;


//reads in from the file to create job objects
afile.open(programname);

if(afile.fail()){
    cout <<"file could not be opened " << programname <<endl;
}
while(!afile.eof())
{


    getline(afile,fileinfo);
    int i = 0;

        //cout <<fileinfo[0] <<endl;//gets next letter
        //cout <<fileinfo[2] <<endl;//gets next arrival time
        //cout << fileinfo[4] <<endl;//gets next duration time
    jobs[i].setletter(fileinfo[0]);
    jobs[i].setarrivaltime(fileinfo[2]);
    jobs[i].setduration(fileinfo[4]);
    i++;


}

afile.close();

cout << jobs[1].getletter() <<endl;
cout << jobs[2].getletter() <<endl;
cout << jobs[3].getduration() <<endl;

right now when i go in and print out the values in my different objects(like at the bottom of the code)after i close the file they all contain the information from the first line of the file. i dont know why because technically i increase 'i' after i set all the values of the job and then fileinfo gets the nextline of the file, so this to me seems like it should work. But like the values i get from those 3 couts at the bottom the results are

A

A

0

the Job class

Job::Job(){}

Job::Job(char let, int arrive, int dura){
  letter = let;
  arrivaltime = arrive;
  duration = dura;
}

and it also has all its get and sets defined so can u guys please help me be able to read in from the file correctly and create my object array


Solution

  • int i = 0;
    

    Each time through the loop, i gets initialized to zero. Immediately after initializing i to 0, your code does this:

    jobs[i].setletter(fileinfo[0]);
    jobs[i].setarrivaltime(fileinfo[2]);
    jobs[i].setduration(fileinfo[4]);
    

    i will always be zero, here. This is what you're seeing. Your computer will always do exactly what you tell it to do, instead of what you want it to do. This is a good rule of thumb for you to keep in mind, going forward.

    i++;
    

    This doesn't matter, because on the next iteration of the while loop, i will be initialized to 0 again. See above.

     while(!afile.eof())
    

    And, this is going to be your second bug, also, which you will immediately discover after fixing your first bug (initialize i before the loop, not inside it).