【问题标题】:Reading a txt file into a struct and displaying the array将 txt 文件读入结构并显示数组
【发布时间】:2013-10-14 03:03:57
【问题描述】:

我无法从文本文件中获取信息并将其放入我创建的结构中,然后显示数组。到目前为止,我创建了结构并创建了带参数的函数,但它似乎不起作用。如果你能把我引向正确的方向,那就太好了。

#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;
}

这是我的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

【问题讨论】:

    标签: c++ arrays struct compiler-errors


    【解决方案1】:

    for(int i = 0; i &lt;= N; ++i) 中建议i &lt; N 而不是i &lt;= N

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-02-15
      • 2016-06-11
      • 2021-03-15
      • 1970-01-01
      • 2015-04-16
      • 2013-12-11
      • 1970-01-01
      相关资源
      最近更新 更多