读取文本文件并存储到数组中

时间:2021-06-05 19:25:46

标签: c++ arrays sorting

我有一个 .txt 文件,其中包含写入数组的内容。但是如果程序关闭,数组的内容当然会被删除,因此我需要读取.txt文件来“提醒”数组之前的内容。

这是我的代码:

#include <fstream>

unsigned short int highscores[11]{0};

int main()
{
    highscores[0] = score;
    std::sort(highscores, highscores + 11);
    std::ofstream outputFile("scores.txt", std::ios::trunc);
    for (short int i = 10; i > 0; i--) {
        outputFile << highscores[i] << std::endl;
    }
    outputFile.close();
}

这是我的 scores.txt 文件:

22
15
13
10
5
5
3
1
1
1

也欢迎对此代码提出任何建议!

1 个答案:

答案 0 :(得分:0)

您只是在文件中写入而不是在读取。如果您关闭程序并重新启动它,您的数组将像您说的那样为空。所以如果你想从你写入的文件中读取文件,你必须使用

std::ifstream inputFile("scores.txt",std::ios::in);

那么读取文件的方法有很多种。 一种是声明一个字符串:

std::string line;

然后使用 while 循环和 getline。

使用短整数高分[11]{0}; int i=0; 而(getline(输入文件,行) { highscores[i]=stoi(line); // stoi 表示字符串到整数。我们使用它是因为 line 是一个字符串但我们需要数字

}