首页 > 解决方案 > 格式化 .txt 文件中的字符串 (C++)

问题描述

unformatted_grades.txt: 未格式化的成绩文件的图像

formatted_grades.txt: 格式化成绩文件的图像

我正在做一个任务,我的教授希望我打开并阅读一个包含不同字符串的 .txt 文件。我们应该格式化文件的内容。

例如:read_grade_file 方法有一个参数 int number_of_students
文件的第一行是“number_of_students 9”

我已经打开并阅读了文件并将每一行推入一个字符串向量。

如何自己获取第一行中的数字 9,以便使 number_of_students 参数等于它???请帮忙。

(我们可以跳过或删除向量中的任何不相关数据)。

我的代码:

void Read_Grade_File(string names[MAX_CLASS_SIZE][2], int scores[MAX_CLASS_SIZE][MAX_NUMBER_OF_ASSIGNMENTS], int *number_of_students, int *number_of_assignments, const string input_filename) {

    string currline; // temporarily holds the content of each line read from the file
    ifstream inFile; // filestream
    vector<string> content; // vector containing each string from the file

    inFile.open(input_filename); //open the file.

    if (inFile.is_open()){
        // reads file and pushes the content into a vector
        while(!inFile.eof()){
            getline(inFile, currline);
            if(currline.size() > 0){
                    content.push_back(currline);
                }
            }
        }
        // prints the content stored in the vector
        for (int i = 0; i < content.size(); i++){
            cout << content[i] << endl;
        }

    }

标签: c++fileformat

解决方案


与其一次读取整行,不如在进行时读取行上的各种值可能更有意义。例如,如果您知道文件的格式,则可以读取第一个变量的名称,然后读取变量的值,如下所示:

std::string variableName;
int variableValue;
inFile >> variableName;
inFile >> variableValue;

因此,您可以获取您知道名称的变量,找到它们的值,然后循环读取文件的其余部分,读取那么多记录。


推荐阅读