C++附加到字符串并写入文件

Mar*_*lor 3 c++ string file-io file

为什么以下代码不起作用

#include <iostream>
#include <fstream>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
using namespace std;

int main(){
    string data;
    int i=0;

    while(i <= 5){
      i++;
      data += i;
      data += "\n";
    }

    ofstream myfile;
    myfile.open ("data.txt");
    myfile << data;
    myfile.close();
}
Run Code Online (Sandbox Code Playgroud)

应该附加一个数字然后换行并将其写入文件(尚不存在).

该文件应该如下所示......

1
2
3
4
5
Run Code Online (Sandbox Code Playgroud)

代码有什么问题?

Kir*_*sky 11

你为什么不用operator<<

ofstream myfile;
myfile.open ("data.txt");
for ( int i = 1; i <= 5; ++i )
  myfile << i << "\n";
myfile.close();
Run Code Online (Sandbox Code Playgroud)