为什么以下代码不起作用?
#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
这段代码有什么问题?
<stdio.h>
应该替换为<iostream>
,<string.h>
应该替换为<string>
,<stdlib.h>
应该替换为<cstdlib>
。如果你参考的是一本书,那么你需要一本新的书。 :) 推荐阅读 Accelerated C++,请参见这里:https://dev59.com/_3RC5IYBdhLWcg3wK9yV。 - John Dibling