zoukankan      html  css  js  c++  java
  • 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
    
  • 相关阅读:
    实用工具---制作试卷
    RDP Client 参数含义调查
    xenserver 虚拟机定时开关机实现
    xenserver 脚本学习之/opt/xensource/bin/xapi-autostart-vms
    最佳的前端监听事件触发方式
    前端之Angularjs
    网页分享
    面试题之事务
    Spring Security安全访问控制解决方案的安全框架
    docker部署
  • 原文地址:https://www.cnblogs.com/spmt/p/11899669.html
Copyright © 2011-2022 走看看