如何使c++函数每次被调用时都写在输出文件的最后一行
How to make c++ function write on the last line of the output file each time it is called
问题是如何使输出文件的第一行有1
,第二行有2
等等,因为每次执行循环时,程序都会重写文件,而输出文件中只剩下9
。
#include <fstream>
using namespace std;
void function (int i)
{
ofstream output("result.out");
output << i << endl;
output.close();
}
int main()
{
for (int i=1; i<10; i++)
{
function(i);
}
return 0;
}
将std::ios::app
作为第二个参数传递给std::ofstream
构造函数。即
std::ofstream output("result.out", std::ios::app);
如果你真的想用自己的方式:
void function (int i)
{
ofstream output("result.out", std::ios::app);
output << i << endl;
output.close();
}
int main()
{
for (int i=1; i<10; i++)
{
function(i);
}
return 0;
}
添加ios:app不会擦除文件的内容,但会在文件中附加文本。它有一个缺点-如果你想再次调用循环,旧数据仍然存在。
但我建议将for()循环移到函数中。
void function (int i)
{
ofstream output("result.out");
for(int j = 1, j < i; j++
output << j << endl;
output.close();
}
int main()
{
function(10);
return 0;
}
结果是一样的,您可以避免重复打开和关闭文件,并且仍然可以将其用作函数。
相关文章:
- 读取文件的最后一行并输入到链接列表时出错
- std::ifstream 在读取文件中最后一项时设置 eofbit,但仅在读取数值类型时发生
- 如何在写入文件时擦除最后一个逗号
- 仅读取文件末尾的最后 3 个字符,并将其另存为 int
- 将文件内容存储到unordered_map仅存储最后的项目和值
- 我的C++程序只写入文本文件最后一个条目
- 程序应该显示文件的最后5行,但它不适用于大文件
- 读取最后一个整数文件C++
- 带有文件结束函数的 while 循环重复输出文件中的最后一个数字两次
- 输入文件中的第一个字符是输出文件中的最后一个字符,反之亦然
- 我的C++文件期望用'while'代替 if。最后,它预计会出现'('
- SFML 将图像从 txt 文件加载到矢量中仅加载最后一个图像
- 如何有效地读取C 中的最后一行文件
- CMake 意外地将最后一个文件名预置到可执行文件中
- 当该应用程序中加速文件的最后一个修改时间发生更改时,如何重新启动应用程序
- 如何确定输入文件中的一行是否是最后一行?C++
- 为什么 fstream 打印出文件的最后一条记录
- 如何在不使用System()的情况下使用C 删除除最后10个文件外的所有文件
- C++ 输出在读取文本文件时跳过最后一个单词
- C++2d数组,用文件中最后一个元素值填充所有元素