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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM