简体   繁体   中英

Reading files using some Pyhton or any script and converting data into C++ key=>value pair (STL maps)

I'm trying to read data from a file line by line and read some specific data from it and than store that data into c++ stl maps as a key value pair.

for example:- let's say we have a file raw_data.inc which consists of following data:-

//
This file consists data of players
Players data
#define David     data(12345) //David's data
#define Mark      data(13441) //Mark's data
Owners data
#define Sarah     data(98383) //Sarah's data
#define Coner     data(73834) //Coner's data
This is the end of the file
//

let's suppose all the above data is stored in the file which we want to read (assume forward slashes are also the part of data). So what I want is to read some part of it(to be specific David and 12345 ) and store it into a c++ stl map as a key value pair

map <string,string> mp

and data will be stored as

mp[12345=>"David",13441=>"Mark",98383=>"Sarah",73834=>"Coner"];

So my question is, is it possible to do so? And if yes than how? Will the normal filestream of C++ will work?

Assume we don't know what is the datatype of the data stored in that file. File could be.h file or.cpp file or.inc file

It is not quite clear what you are actually trying to do. However, if you merely want to read the contents of the file into a std::map at runtime, then you just have to parse the lines of the file:

#include <iostream>
#include <string>
#include <sstream>
#include <map>

int main() {
    //
    std::stringstream ss{R"(#define David     data(12345)
#define Mark      data(13441)
#define Sarah     data(98383)
#define Coner     data(73834))"};

    std::map<std::string, std::string> m;
    std::string line;
    while (std::getline(ss,line)){
        std::string dummy;
        std::string name;
        std::string data;
        std::stringstream linestream{line};
        linestream >> dummy >> name >> data;
        auto start = data.find('(');
        auto stop = data.find(')');
        m[data.substr(start+1,stop-start-1)] = name;
    }
    for (const auto& e : m) {
        std::cout << e.first << " " << e.second << "\n";
    }
    return 0;
}

You merely have to replace the stringstream with an ifstream .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM