Search code examples
c++fileifstreamfriend

Extracting specific value (char & int) from a text file and inserting into multiple variables C++


Below is the file I need to extract data from.

    auto1
    engine: gasoline
    max_speed: 250
    engine_cc: 1980
    avg_consumption_urban: 11
    avg_speed_urban: 50
    avg_consumption: 8
    avg_speed: 100
    auto2
    engine: diesel
    max_speed: 230
    engine_cc: 1600
    avg_consumption_urban: 9
    avg_speed_urban: 50
    avg_consumption: 6
    avg_speed: 80
    auto3
    engine: hybrid
    max_speed: 190
    engine_cc: 1450
    avg_consumption_urban: 7
    avg_speed_urban: 50
    avg_consumption: 4
    avg_speed: 90

I need to create three auto objects, auto1, auto2, auto3.

The code I have so far:

[my code] http://pastebin.com/2TMhQX9b

I need to modify this method to skip over the "engine:", "max_speed:" ... etc and get the information that is after those attribute titles and insert the respective value in the corresponding attribute.

Also I need to find a way for the compiler to know for example when creating auto2 to get the information for auto2 and not auto1 from the file

    friend ifstream& operator>>(ifstream& in, Auto &a)
        {
            delete[]a.engine;
            a.engine = new char[10];
            in >> a.engine;
            in >> a.max_speed;
            in >> a.engine_cc;
            in >> a.avg_consumption_urban;
            in >> a.avg_speed_urban;
            in >> a.avg_consumption;
            in >> a.avg_speed;
            return in;
        }

This question is different from my previous question. Here I need to find out how I can get my data from the file and insert it into multiple variables.


Solution

  • One way to solve this is to read one line (for e.g. auto1 etc.), then use your custom operator>> function to read the actual data for the object, probably much like you do already.

    The input operator function needs to be changed a bit from what you have now though. You can continue on a similar way like you do know, but you first need to read every lines "tag" (e.g. engine: or max_speed:), the simplest is to do it something like this:

    std::string dummy;
    in >> dummy >> a.engine;
    in >> dummy >> a.max_speed;
    

    I would probably not do like that, because what if some other program writes this file in the wrong order from what you currently read it? Instead I would probably, again, read one line at a time, and split the input into two sub-strings on the ':' character, the "tag" or "key, and the value. Then you could check the key to see what value to assign to in the structure.

    For converting strings to an integer, there is a nice function to help you.

    For example:

    if (key == "max_speed")
        a.max_speed = std::stoi(data);