Fill struct array from text file

Hi,

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.

Extract of code below:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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?

Thanks
Crimson
Sure, you can put the for loop inside readFile
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
struct employee
	{
		string name;
		int id;
		float salary;
	};

void readFile(struct employee employeeArray[]);

int main()
{	
	int SIZE = 5;

	employee employeeArray[SIZE];

	readFile(employeeArray);
	
	return 0;
}

void readFile(struct employee employeeArray[], size_t size)
{
	ifstream in;
	in.open(file);

	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;
		}
	}
	// maybe return the number of records successfully read.
}

Thanks for the quick reply!

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;


Thanks
Crimson
> 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.

In general, you need to check input was successful before doing any other processing on it.
Otherwise, it's https://en.wikipedia.org/wiki/Garbage_in,_garbage_out

Thanks for the help!
>"Is there a way to read one line at a time?"
yes. use getline()
1
2
3
4
5
6
7
8
9
10
#include <fstream>
#include <string>

int main(){ 
	std::ifstream file("input.txt");
	std::string str; 
	while (std::getline(file, str)){
		//code
	}
}
Topic archived. No new replies allowed.