如何把string数组写入txt文件?(C/C++)

我已经有了一个string word[n]数组,每个单元保存了一个单词。
现在需要把它们输出到一个txt文件中,要求写一个换一行。
但怎么整都不行,试了fprintf()和fwrite()都失败了,输出在文件中的要么都是字符串“NULL”要么就是空的。。。坐等高人指教~
--------------------------------------代码在这,写出来的是乱码和空白,哎
#include<iostream>
#include<string>
#include<fstream>
using namespace std;

int main()
{
string word[4];
word[0] = "What";
word[1] = "a";
word[2] = "f*cking";
word[3] = "day";

FILE *pfOutput;
pfOutput = fopen("output.txt", "wt");
if (pfOutput == NULL)
cout << "Error!" << endl;
else
cout << "output.txt open success~" << endl;

for(int i=0; i<4; i++)
{
fwrite(&word[i], word[i].length(), 1, pfOutput);
fprintf(pfOutput, "\n" );
}

return 0;
}

你只需要修改循环体内就可以了。改为:
for(int i=0; i<4; i++)
{
// fwrite(&word[i], word[i].length(), 1, pfOutput);
fprintf(pfOutput, "%s\n",word[i].c_str());
}
原因是:int fprintf(FILE *stream, const char *format, ...);fwrit也一样哦,
函数入参类型是char* 。而你的入参是string类型的word[]
string str1.c_str() 等同于char* str1
string str1 不同于char* str1
呵呵,给点分哦!谢谢!
温馨提示:答案为网友推荐,仅供参考
第1个回答  2011-11-01
把完整代码贴出来。问题应该是你数组储存的格式和fprintf不一致造成的。
第2个回答  2011-11-01
用C++的fstream的I/O流读写文件可以么,可以的话我可以帮你实现追问

当然可以了,任何C或C++的办法都欢迎啊!

相似回答