jenthu
jenthu

Reputation: 13

How to read lines of a file into an array of structs

I am trying to read a file which contains the arrival time and burst time of 22 processes in every line.I am trying to store these values into an array of structs so I can update them everytime a process gets a CPU cycle.The read is not working successfully though.Help me figure out what I am missing. The file which is a text file looks like: 30 0.78 \n 54 17.28 \n 97 32.82 \n . . . .

#include<iostream>
#include<fstream>

using namespace std;        
const int process_cnt=22;

struct process{        
          int at;
          float bt;
          float rt;
};

process init_q[process_cnt],ready_q[process_cnt];        
void getData(ifstream& inData,process init_q[]);

int main(){        
    ifstream inData;        
    getData(inData,init_q);                
    cout<<"Test";        
    return 0;
}

void getData(ifstream& inData,process init_q[]){                        
    inData.open("input.txt");        
    while(inData){          
        inData>>init_q->at>>init_q->bt;
        cout<<init_q->at<<" "<<init_q->bt<<endl;//check if read was succesful           
    }
    inData.close();         
}

Upvotes: 0

Views: 74

Answers (1)

woockashek
woockashek

Reputation: 1638

Probably what you are missing is the index of current array entry:

void getData(ifstream& inData, process init_q[]) {
    inData.open("input.txt");
    int index = 0;
    while (inData) {
        process *entry = init_q[index++];
        inData >> entry->at >> entry->bt;
        cout << entry->at << " " << entry->bt << endl;//check if read was succesful
    }
    inData.close();
}

I skipped the part checking whether the current index is lower than your const 22.

Upvotes: 2

Related Questions