C++ 从txt文本中读取map

由于存入文本文件的内容都为文本格式,所以在读取内容时需要将文本格式的内容遍历到map内存中,因此在读取时需要将文本进行切分(切分成key和value)

环境gcc

#include<iostream>
#include<fstream>
#include<string>
#include<map>
#include<utility>
#include<vector>
#include<cstring>

using namespace std;
//分割字符串
vector<string> split(const string& str, const string& delim){
    vector<string> res;
    if("" == str) return res;
    //先将要切割的字符串从string类型转换为char*类型
    char * strs = new char[str.length() + 1];
    strcpy(strs, str.c_str());

    char * d = new char[delim.length() + 1];
    strcpy(d, delim.c_str());

    char *p = strtok(strs, d);
    while(p){
        string s = p;  //分割得到的字符串转换为string类型
        res.push_back(s); //存入结果数组
        p = strtok(NULL, d);
    }
    return res;
}

int main(){
//根据key从文件中读出相应的value
    map<string, string> myMap;
    ifstream ous("text.txt");
    while(!ous.eof()){
        string temp;
        ous>>temp;
        vector<string> tempstr = split(temp ,"=");
//        for(int i=0;i<tempstr.size(); i++){
//        }
        string key = tempstr[0].c_str();
        string value = tempstr[1].c_str();
        myMap.insert(make_pair(key,value)); //将字符串转换为键值对
    }
    for(map<string, string>::iterator itr=myMap.begin();itr!=myMap.end();itr++){
        cout<<itr->second<<endl; //
    }
    return 0;
}

txt文件格式

你=69
再见=40
小娜=76
小通=76
好佩服你啊=71
加油=64
我很高兴=80
欢迎你的到来=56
你真厉害=71
查询不到=70
说点别的=70

原文链接: https://www.cnblogs.com/spmt/p/11899669.html

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍

    C++ 从txt文本中读取map

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/306178

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年2月16日 上午3:41
下一篇 2023年2月16日 上午3:45

相关推荐