C++ 如何制作c++;每次调用输出文件时,在最后一行写入函数
问题是如何使输出文件的第一行有C++ 如何制作c++;每次调用输出文件时,在最后一行写入函数,c++,fstream,ofstream,C++,Fstream,Ofstream,问题是如何使输出文件的第一行有1,第二行有2,等等。因为每次执行循环时,程序都会重写文件,而输出文件中只剩下9 #include <fstream> using namespace std; void function (int i) { ofstream output("result.out"); output << i << endl; output.close(); }
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;
虚函数(int i)
{
流输出(“result.out”);
输出传递std::ios::app
作为std::ofstream
构造函数的第二个参数
std::ofstream output("result.out", std::ios::app);
将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;
}
void函数(inti)
{
流输出(“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;
}
void函数(inti)
{
流输出(“result.out”,std::ios::app);
输出不是每次都打开和关闭它,也不是每次都用标志打开它。我从来没有真正调用过流的output.close();
,对象跟随RAII,在函数调用结束时自动关闭。不是每次都打开和关闭它,也不是每次都用标志打开它。我从来没有真正调用过output.close()
流的对象跟随RAII,并在函数调用结束时自动关闭。不需要或不需要出
,它会为您完成。@BoBTFish,是的,我不确定,我正在搜索standard的引用…@BoBTFish,您是对的,它是[ofstream.cons]/2:构造一个对象[…],然后调用rdbuf()->open(s,mode | ios_base::out)。我刚刚检查过。没有必要为这一个使用标准。不需要或不需要out
,它会为你做的。@BoBTFish,是的,我不确定,我正在搜索标准的引用…@BoBTFish,你是对的,它是[ofstream.cons]/2:构造一个对象[…],然后调用rdbuf()->打开(s,mode | ios_base::out)。我刚刚检查过。我觉得没有必要为这一个使用标准。