这是我将输入写入文本文件的代码
ofstream fout("C:\\det.txt",ios::app);
fout << input << endl;
fout.close();
这个程序可以运行,但是当我输入多个输入时,它的输出是这样的
输出
four
three
two
在上面的输出中,第二个是我的最后一个条目,第四个是我的第一个条目,但我希望它的顺序相反,最新的输入应该首先出现,比如
要求的输出
two // latest entry
three // 2nd latest entry
four // 3rd entry
最佳答案
将文件内容放入 vector 中,反转 vector 并将字符串重新插入文件中。
std::fstream file("C:\\det.txt", std::ios_base::in);
std::vector<std::string> lines;
std::string line;
while (std::getline(file, line))
{
if (!line.empty())
lines.push_back(line);
}
file.close();
file.open("C:\\det.txt", std::ios_base::trunc | std::ios_base::out);
std::copy(lines.rbegin(), lines.rend(), std::ostream_iterator<std::string>(file, "\n"));
关于c++ - 如何反转文本文件中的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19889989/