这是我将输入写入文本文件的代码
ofstream fout("C:\\det.txt",ios::app);
fout << input << endl;
fout.close();
这个程序正在运行,但是当我输入多个输入时,它的输出就像这样
Output
four
three
two
在上面输出两个是我的最后一个条目,四个是我的第一个条目,但我想以相反的顺序,最新的输入应该首先出现像
Required output
two // latest entry
three // 2nd latest entry
four // 3rd entry
答案 0 :(得分:1)
将文件内容放入向量中,反转向量并将字符串重新插入文件中。
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"));
答案 1 :(得分:0)
如果输入输入后不需要更新文件,则需要缓冲区将输入存储在某处(可能是std::vector<std::string>
),然后以相反的顺序将其写入文件。
你也可以阅读整个文件并每次使用fout << input << endl << readContent;
重写它,但这不是一个好方法,因为每次输入时都会很慢地修改整个文件。