【问题标题】:Writing to a file with map container contents c++ [duplicate]写入具有地图容器内容的文件c ++ [重复]
【发布时间】:2015-01-22 21:58:50
【问题描述】:

我的问题是关于写入包含地图内容的 c++ 文本文件。目前我正在尝试以当前方式写入我的文件:

void toFile()
{
   ofstream outFile;
   outFile.open("random.txt");
   if(outFile.is_open()){
      for(it = mymap.begin(); it != mymap.end(); it++){
         if(mymap.size()!=0){
            outFile << it->second.listInfo() << endl;
            outFile.close();
        }   
        else{
            cout << "An Error has occured" << endl;
        }
      }
   }
}

我的函数 listInfo() 是一个仅打印出我自己实现的类的信息的函数。

void listInfo(){
cout << "NAME: " << name << "Adress " << adress << "Color " << color;
}

我的问题是当我使用:it-&gt;second.listInfo() 写入我的文件时出现错误,但是当我使用 it-&gt;first 时却没有出现错误。有人可以解释一下为什么我的代码会产生错误并且没有将我的子类中的信息列出到我的文件中吗?

【问题讨论】:

  • 你的函数返回void。您正在尝试将void 打印到文件中。这没有意义。
  • 什么是mymap? if(mymap.size()!=0) 是没用的,因为你的 for 循环只会在你的“mymap”(地图?)中有东西时迭代。
  • @JeromeL mymap 是我实现的地图容器的名称。是的,感谢您提供的这些信息,我一直在尝试以几种不同的方式进行编码,并且一定是用这种 if-case 来迷惑自己。感谢您提供相关信息。

标签: c++ dictionary containers fstream ostream


【解决方案1】:

您似乎没有在写入文件:

outFile << it->second.listInfo() << endl;

// This doesnt return anything it simply writes to standard out. 
void listInfo(){
  cout << "NAME: " << name << "Adress " << adress << "Color " << color;
}

您可能希望执行以下操作:

void YourClass::listInfo(std::ofstream ) {
    out << "NAME: " << name << "Adress " << adress << "Color " << color << endl;

}


it->second.listInfo(outFile);

这样您的数据可以成功地流式传输到文件中。

【讨论】:

  • 干杯,感谢它成功地帮助了我的代码和我的故障排除,直到下一次! Void 不会打印任何内容。 @本
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-29
  • 2017-03-12
  • 2014-03-21
  • 1970-01-01
  • 2014-11-20
  • 2015-08-20
  • 2012-02-19
相关资源
最近更新 更多