c++ - 如何反转文本文件中的输出

标签 c++ visual-c++ text-files

这是我将输入写入文本文件的代码

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/

相关文章:

c++ - python zlib 输出到 C++ 字符串

c++ - 对于 char d,我在执行 cout << &d 时得到奇怪的输出

c++ - 在 foreach 循环中将指针隐式转换为 std::unique_ptr

excel - 如果您在 Windows 资源管理器中右键单击并使用 Excel 打开,如何在 Excel 中打开 txt 文件?

java - 使用字节流写入文件

c++ 二维数组非常规网格插值

c - 递归函数中的堆栈溢出(C语言)

c++ - Lambda Capture by Value 强制所有作用域对象为 const

c++ - 这段C++代码有什么问题?

java - 如何从存储在 txt 文件中的 rgb 数据创建 bmp 文件?