简体   繁体   English

使用一些 Pyhton 或任何脚本读取文件并将数据转换为 C++ 键=>值对(STL 映射)

[英]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.我正在尝试逐行读取文件中的数据并从中读取一些特定数据,然后将该数据作为键值对存储到 c++ stl 映射中。

for example:- let's say we have a file raw_data.inc which consists of following data:-例如:-假设我们有一个文件 raw_data.inc,其中包含以下数据:-

//
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所以我想要的是读取它的某些部分(具体是David12345 )并将其存储到 c++ stl map 作为键值对

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? C++ 的正常文件流会起作用吗?

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文件可以是.h文件或.cpp文件或.inc文件

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:但是,如果您只想在运行时将文件的内容读入std::map ,那么您只需解析文件的行:

#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 .您只需将 stringstream 替换为ifstream

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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