gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 19:39:55 24 4
gpt4 key购买 nike

为什么下面的代码不起作用

#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();
}

应该附加一个数字然后换行符并将它写入一个文件(这不会'还不存在)

文件应该是这样的...

1
2
3
4
5

代码有什么问题?

最佳答案

为什么不用operator<<

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

关于C++追加到字符串并写入文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3558669/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com