首页 > 解决方案 > 将由空格分隔的数据读入结构数组

问题描述

我很难从 txt 文件中读取数据并将其转换为结构数组。数据的格式如下:

John Doe MATH 4 3 4 3 2
John Peterson MATH 5 5 3 6 2
...

目前,我只能读取不超过NLENGTH 个字符,其中应该是一个分隔符(至少在NLENGTH + 1 个位置)。但是,如果有一个名称/专业长于NLENGTH的记录,我的代码将停止正常工作。下面代码的输入如下所示:

    John Doe # MATH # 4 3 4 3 2
    John Peterson# MATH#  5 5 3 6 2
    Michele Jordan # Electrical Engeeniring # 8 7 9 0 3 // Fail on this line
    John Dore# MATH# 5 4 3 2 1
    John Dore# Biology #9 3 4 2 3
const int NMARK = 5;
const int NLENGTH = 20;
const int NSTUDENT = 100;
const char dataDelimeter = '#';
void from_txtFile(const char *filename, Student *stArray)
struct Student {
    char name[NLENGTH];
    char major[NLENGTH];
    int mark[NMARK];
};
int main()
{
    Student stArray[NSTUDENT];
    char fileName[20] = "data.txt";

    from_txtFile(fileName, st);
}
void from_txtFile(const char *filename, Student *stArray) {
    ifstream data(filename, ios::in);
    int recordCount = 0;
    if (!data) cout << "Error" << endl;
    while (data && (recordCount < NSTUDENT)) {
        data.getline(stArray[recordCount].name, NLENGTH, dataDelimeter);
        data.getline(stArray[recordCount].major, NLENGTH, dataDelimeter);
        for (int i = 0; i < NMARK; i++)
            data >> stArray[recordCount].mark[i];
        // Output
        cout << stArray[recordCount].name << ' ';
        cout << stArray[recordCount].major << ' ';
        for (int i = 0; i < NMARK; i++)
            cout << stArray[recordCount].mark[i] << ' ';
     }
     recordCount++;
     data.close();
}

标签: c++

解决方案


推荐阅读