c++ - 写入具有 map 容器内容的文件 C++

标签 c++ dictionary containers fstream ostream

<分区>

我的问题是关于将 map 内容写入一个 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->second.listInfo() 写入我的文件时出现错误,但是当我使用 it->first 时我没有收到错误。有人可以解释为什么我的代码会产生错误并且没有将我的子类中的信息列出到我的文件中吗?

最佳答案

您似乎没有在写入文件:

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);

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

关于c++ - 写入具有 map 容器内容的文件 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28099451/

相关文章:

azure - 通过 SSH 连接到 Azure 的 Kubernetes 托管主节点

c++ - 如果使用#define 没有任何赋值,它会做什么?

c++ - 将 char 添加到字符串会导致 C++ 崩溃

c++ - C和C++中return 0有什么意义?

python - 如何将嵌套的 OrderedDict 转换为字典?

python - 尝试将不同的项目附加到列表中

c++ - 是否有用于建模发布者 - 订阅者关系的容器,并且可以快速查找其中任何一个?

C++ 结构默认构造函数

python - 我在 python 中遇到关键错误

css - "Perfectly"矩形动态文字