繁体   English   中英

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

[英]How to read different types of data from text file to several arrays ? C++

这是一个名为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

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

#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        

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

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

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

您的特定示例可以这样写:

// 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
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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