Copy data from text file into array

Hi! I am trying to build a code to read the data from a text file into the array and display all records but it is not working and I am not sure how to fix the issues or how to even correctly use the file name as a parameter. Any tips would be greatly 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
#include <iostream>
#include <fstream>
using namespace std;

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

void CopyRecords (char Name, int x[], int n);
void Display (RECORD x[], int 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 (char Name, int x[], int n)
{	
	fstream f; 
	f.open ("data2.txt");
	for (int i = 0; i < n; ++i)
	{
		f >> x[];
	}
}
void Display (RECORD x[], int n)
{
	for (int i = 0; i < n; ++i)
	{
		cout << x[i].Name << " " << x[i].Age << " " << x[i].Gpa << '\n';
	}
}
Last edited on
Hello! I have come up with this now:
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
#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[N]);
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[N])
{
	ifstream f;
	f.open(filename, ios::in);
	
	for(int i = 0; i <=5; ++i)
	{
		f >> p[i].Name;
	}
}
void Display (RECORD x[])
{
	for (int i = 0; i < N; ++i)
		cout << x[i].Name << " " << x[i].Age << " " << x[i].Gpa << endl;
}


My output shows:
Martin 0 0
Smith/ 0 0
22 0 0
2.2 0 0
Austin 0 0

When it needs to show:
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


Anyone have any ideas on what I can fix?
because you only extract the name and not the values ?

And another:
for ( int i = 0; i <= 5; ++i ) should be

for ( int i = 0; i < 5; ++i ) since your array size is 5 and p[5] is i

think should be leaved since it is used to store NULL

and use different variable name for your structure parameter in CopyRecord() and display()
Last edited on
Topic archived. No new replies allowed.