【问题标题】:Saving map<string,int> to text file将 map<string,int> 保存到文本文件
【发布时间】:2020-07-26 09:57:47
【问题描述】:

我有一个字符串 int 映射,我想将它保存到 txt。我有一段时间没用过 c++ 了,我对指针之类的东西很迷茫。

int WriteFile(string fname, map<string, int>* m) {
    int count = 0;
    if (m->empty())
        return 0;

    FILE* fp = fopen(fname.c_str(), "w");
    if (!fp)
        return -errno;

    for (map<string, int>::iterator it = m->begin(); it != m->end(); it++) {
        fprintf(fp, "%s=%s\n", it->first.c_str(), &it->second);
        count++;
    }

    fclose(fp);
    return count;
}

问题是整数被写成垃圾字符。

【问题讨论】:

    标签: c++ string visual-studio dictionary fopen


    【解决方案1】:

    %s 用于打印字符串,您通过将错误类型的数据传递给fprintf() 来调用未定义的行为

    您应该使用%d 格式来打印int

    fprintf(fp, "%s=%d\n", it->first.c_str(), it->second);
    

    【讨论】:

    • 啊哈,我知道我很接近了,谢谢。我确实尝试使用'n'而不是's',没有看到'd'。
    【解决方案2】:
    #include<map>
    #include<fstream>
    #include<iostream>
    
    using namespace std;
    
    int WriteFile(string fname, map<string, int> &m) {
        
        if (m.empty()) return 0;
        
        ofstream fout;
        fout.open(fname);
        
        if(!fout) return -errno;
        
        int count = 0;
        for (auto it = m.begin(); it != m.end(); it++) {
            fout<<it->first<<" = "<<it->second<<"\n";
            count++;
        }
    
        fout.close();
        return count;
    }
    
    int main()
    {
        map<string, int> m;
        m["Hi there"]=1;
        m["How are you"]=-7;
        m["I am fine"]=-9;
        m["Yo"]=15;
        m["Code"]=2;
        
        
        WriteFile("testing", m);
        return 0;
    }
    

    您确实需要使用指针表示法来通过引用传递。只需在函数参数中将&amp; 添加到m 即可轻松完成

    【讨论】:

      猜你喜欢
      • 2021-09-17
      • 2018-03-02
      • 1970-01-01
      • 2016-10-07
      • 2018-05-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-27
      相关资源
      最近更新 更多