简体   繁体   中英

Reading a txt file into a struct and displaying the array

I'm having trouble grabbing information from a text file and putting it into the struct that I created and then displaying the array. So far I created the struct and created the functions with parameters, but it doesn't seem to be working. If you could steer me in the right direction, that'd be great.

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

const int N=5;

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

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

int main()
{
    RECORD p[N];

    //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, int p[N])
{
    ifstream f;
    f.open(filename, ios::in);

    for(int i = 0; i <= N; ++i)
    {
        f >> p[i];
    }
}
void Display (RECORD x[])
{
    for (int i = 0; i < N; ++i)
        cout << x[i].Name << " " << x[i].Age << " " << x[i].Gpa << endl;
}

This is my 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

for(int i = 0; i <= N; ++i)建议i < N而不是i <= N

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM