首页 > 编程语言 > 详细

C++ 从txt文本中读取map

时间:2019-11-20 19:04:59      阅读:261      评论:0      收藏:0      [点我收藏+]

废话不多说直接上代码

#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

C++ 从txt文本中读取map

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!