如何使c++函数每次被调用时都写在输出文件的最后一行

How to make c++ function write on the last line of the output file each time it is called

本文关键字:最后 文件 输出 一行 函数 c++ 何使 调用      更新时间:2023-10-16

问题是如何使输出文件的第一行有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;
}

结果是一样的,您可以避免重复打开和关闭文件,并且仍然可以将其用作函数。