c++怎样实现数据存入指定的TXT文档

 我来答
百度网友3a00d8c64
2016-11-06 · TA获得超过599个赞
知道小有建树答主
回答量:430
采纳率:64%
帮助的人:332万
展开全部

1、类似于以下代码:

2、需要<fstream>头文件

3、主要是ofstream类的对象的操作。

void CNews::save(string fileName)
{
 ofstream outfile(fileName.c_str());
 string ar;
 if(!outfile)
 {
  cerr << "error:unable to open input file:" << outfile << endl;
  return;
 }
 //format_save
 for(mapIter it=newsGroup.begin();it!=newsGroup.end();it++)
 {
  outfile << it->first
    << endl
    << it->second.first
    << endl;
  for(vector<string>::iterator vIt=it->second.second.begin();vIt!=it->second.second.end();vIt++)
   outfile << *vIt;
  outfile << endl;
 }
 outfile.close();
}

 4、理所当然地可以缩减成以下代码,上述的是我以前写的类的文件保存函数

#include<fstream>
using namespace std;
int main()
{
    ofstream outfile("filename.txt");
    if(!outfile)
     {
      cerr << "error:unable to open input file:" << endl;
      return;
     }
     outfile << "C++ program .file version." << endl;
     outfile.close();
}
推荐律师服务: 若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询

为你推荐:

下载百度知道APP,抢鲜体验
使用百度知道APP,立即抢鲜体验。你的手机镜头里或许有别人想知道的答案。
扫描二维码下载
×

类别

我们会通过消息、邮箱等方式尽快将举报结果通知您。

说明

0/200

提交
取消

辅 助

模 式