Reading file into arrays


I have a text file like this:
Williams,Leonard Freshman 1.85
Smith,Sheila Senior 2.99
Anderson,Andy Sophomore 3.01

and i want to read those names and their year and numbers into a 3 arrays and then show them on the screen, but it only shows the first name, can anyone help with looping through all the names


here is my code so far:

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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
  #include <iostream>
#include <fstream>
#include <string>


using namespace std;


void Read(string& Name, string& Year, float& GPA)
{
	ifstream inputFile;
	inputFile.open("list.txt");



		while (inputFile >> Name >> Year >> GPA);
	
}














int main()
{

	string studentName[25], studentYear[25];
	float studentGPA[25];

	for (int i = 0; i < 25; i++)
	{
		Read(studentName[i], studentYear[i], studentGPA[i]);

		cout << studentName[i] << "   " << studentYear[i] << "   " << studentGPA[i] << endl;

	}



	





	system("PAUSE");
	return 0;
}
The big issue you have is that every time you call the Read function in your i loop, you end up re-opening the list.txt file. This means that every time Read is called, it grabs values from the beginning of the file, hence only getting the details of the first name over & over again.

You only want to open the file once, outside of your i loop.

You also should close the file after your i loop.

And inside your i loop, you should be checking whether you have reached the end of the file (for example, by querying the result of inputFile.good() ). You want to stop reading from the file if you reach the end of it.

You could also use adding some bomb-proofing to the file opening & reading, but the above things should get you going in the right direction.
Topic archived. No new replies allowed.