0

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

Rav
  • 75
  • 9
  • 3
    To be clear, do you want to read the file at runtime or compile it into your C++ program? Currently the file has preprocessor directives. Is this a given or can you change the format of the file? Are the player and owner names fixed or should they also be read from the file? – Sebastian Jan 17 '22 at 11:19
  • You can look into this https://stackoverflow.com/a/67416749/10340933 – subrata Jan 17 '22 at 11:53

1 Answers1

1

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.

463035818_is_not_an_ai
  • 109,796
  • 11
  • 89
  • 185