【发布时间】:2020-05-19 16:21:15
【问题描述】:
我想通过几个单独的调用将一些数据打印到文件中。我注意到写入的默认行为会覆盖以前写入的数据。
#include <iostream>
#include <fstream>
using namespace std;
void hehehaha (){
ofstream myfile;
myfile.open ("example.txt");
myfile << "Writing this to a file.\n";
myfile.close();
}
int main () {
for(int i=0; i <3 ; i++){
hehehaha();}
return 0;
}
这段代码只写了一行Writing this to a file.,但我想要的是以下内容:
Writing this to a file.
Writing this to a file.
Writing this to a file.
【问题讨论】:
-
检查 ofstream
open方法的mode参数 -
一个选项:以追加模式打开文件。
-
非常感谢@Kryten 和 Johnny