如何从文本文件到多个数组读取不同类型的数据? C ++

时间:2017-09-06 05:36:00

标签: c++ arrays

这是一个名为grades.txt的文本文件:

John   Sebastian    90  80   85  90     75 70  89 80 90       86 88 89 99 100  

Brown  Ford         40  60   80  85     60 90 100 80 90       83 81 89 97 90

我需要读取所有数据并将它们放在单独的数组中。前4个等级是考试,第二个是测验,第三个是家庭作业。

#include <iostream>
#include <fstream>

using namespace std;

void letter_grade(string names[][2], int exams[][4], int quiz[][5], int homeworks[][5], float grades[2][2]);

int main() {

ifstream Openfile("grades.txt");


string names[2][2];
int exams[4][4];
int quiz[5][5];
int homeworks[5][5];

if(Openfile.is_open()){
for(int i = 0 ; i<2 ; i++){
    Openfile >> names[i][0];
}
    for(int j = 0 ; j<2; j++){
        Openfile >> names[j][1];
    }
}
    else{
    cout << "File is not open." << endl;
}
if(Openfile.is_open()){
    for(int x = 0 ; x<4 ; x++){
        for(int y = 0; y<4 ; y++){
            Openfile >> exams[x][y];
        }
    }
}


    return 0;
}

所以我计划的阵列将是这样的:

names[0][0] = John
names[1][0] = Sebastian 
names[0][1] = Brown
names[1][1] = Ford        

等等。但我无法做到这一点,而是代码不断阅读考试结果并将其写入名称数组。

然后我将从数组中计算这些学生的成绩,并将结果保存在另一个文件中,如果我可以从文本文件中读取数据,我将会这样做。

1 个答案:

答案 0 :(得分:0)

多维数组不携带单个组件或成员值的语义信息。你必须在数据的含义和头脑中阵列中的位置之间进行转换。而是使用适当的数据结构来使您的代码有意义。

您的具体示例可以这样写:

// the record data
struct StudentScore {
    std::string firstname, lastname;
    int exams[4];
    int quizzes[5];
    int homeworks[5];
};
// parse the text, assuming data is well formatted
StudentScore parse_one_record (std::istream &is) {
    StudentScore score{};
    is >> score.firstname >> score.lastname;
    for (auto &exam: score.exams) is >> exam;
    for (auto &quiz: score.quizzes) is >> quiz;
    for (auto &homework: score.homeworks) is >> homework;
    // consume any trailing whitespaces including LF
    is >> std::ws;
    return score;
}

int main (int, char *[]) {
    auto file = std::ifstream("grades.txt");
    file >> std::ws;
    auto records = std::vector<StudentScore>{};
    // assume the file is well formatted.
    while (!file.eof()) {
        records.push_back(parse_one_record(file));
    }
    // now you can begin processing your data
}