I need to create a struct array, pass by reference into a function, and the fill the array through a text file in this function. My array has five columns, and in each column is a name, id, and salary. Currently, I believe what is happening is the entire text file is being put into each column of the array.
struct employee
{
string name;
int id;
float salary;
};
void readFile(struct employee);
int main()
{
int SIZE = 5;
employee employeeArray[SIZE];
$ for(int i = 0; i < SIZE; i++)
$ readFile(file, employeeArray[i]);
return 0;
}
void readFile(struct employee employeeArray)
{
ifstream in;
in.open(file);
while(!in.eof())
{
in >> employeeArray.name >> employeeArray.id >> employeeArray.salary;
}
}
I think .eof, reads until the end of the text file. Is there a way to read one line at a time?
Otherwise can I call the function without needing a for loop (lines with $), so that each line read becomes a seperate column in the array?
What you suggested seems to work, thank you so much. Just a quick question, if all i need to do is put the data into the array can i remove the if loop?
ie
1 2 3 4 5 6 7
for(int i = 0; i < size; i++) {
if ( in >> employeeArray[i].name >> employeeArray[i].id >> employeeArray[i].salary ) {
// do something
} else {
// input failure or EOF
break;
}
becomes just
in >> employeeArray[i].name >> employeeArray[i].id >> employeeArray[i].salary;
> if all i need to do is put the data into the array can i remove the if loop?
The if is there to check that the input of a particular record was successful.