Copying and Displaying an array from text file

Hi, I'm having a little bit of trouble copying data from a text file and displaying it in an array. Not sure how to proceed further and any help would be appreciated.

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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int N=5;

struct RECORD
{
	char Name[15];
	int Age;
	float Gpa;
};
RECORD p[N];

void CopyRecords (string filename, RECORD &p);
void Display (RECORD x);

int main()
{
	
	//Read data from this file into array p

	CopyRecords("data2.txt",p);

	//Display all records
	Display(p);

	//Terminate Program
	system ("pause");
	return 0;
}
void CopyRecords (string filename, RECORD &p)
{
	ifstream f;
	f.open(filename, ios::in);
	
	for(int i = 0; i <= N; ++i)
	{
		f >> p.Name[i] >> p.Age[i] >> p.Gpa[i]; 
	}
}
void Display (RECORD &x)
{
	for (int i = 0; i < N; ++i)
		cout << x[i].Name << " " << x[i].Age << " " << x[i].Gpa << endl;
}

1
2
3
4
5
6
7
8
9
10
//data2.txt
/*

Martin Smith/ 22 2.2
Austin Clinton/ 18 3.1
Johnson/ 19 2.9
Maggie Jones/ 23 2.3
Tyler W Brown/ 16 3.4

*/
Last edited on

how to proceed further

How about describing in words what you've already done and what you need to do further but do not know how?

It is not good idea to show some code and tell "I stuck somewhere here - and I'm curious what to do"
I found this power point tutorial really helpful. I'm having the same problem with one of my projects, and it lays out step by step.

http://courses.cs.vt.edu/~cs1044/spring03/mcpherson/ArraysofStructs.pdf
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
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int N=5;

struct RECORD
{
	char *Name;
	int Age;
	float Gpa;
};

RECORD p[N];

void CopyRecords (string filename, RECORD p[N]);
void Display (RECORD x[N]);

int main()
{

	//Read data from this file into array p

	CopyRecords("data2.txt", p);

	//Display all records
	Display(p);

	//Terminate Program
	system ("pause");
	return 0;
}
void CopyRecords (string filename, RECORD p[N])
{
	ifstream f;
	f.open(filename, ios::in);
	
	for(int i = 0; i <= N; ++i)
	{
		f >> p[i].Name >> p[i].Age >> p[i].Gpa;
	}
}
void Display (RECORD x[N])
{
	for (int i = 0; i < N; ++i)
		cout << x[i].Name << " " << x[i].Age << " " << x[i].Gpa << endl;
}


This is what I've changed so far. The code won't compile. I think what my issue is I've tried to populate the RECORD struct from the data2.txt, but I believe my issues lie within the CopyRecords function. I don't think its populating correctly.
Topic archived. No new replies allowed.