Search code examples
visual-c++structurefstreamrequirements.txt

Reading a text file into an structure


I'm trying to read some information from a .txt file and then store it in a structure, but I don't know how to do it only selecting the words I need.

The .txt is the following

fstream write_messages("C:\\Messages.txt");

A line in the .txt looks like this:

18 [@deniseeee]: hello, how are you? 2016-04-26.23:37:58

So, the thing is that I have a list of strutures

list<Message*> g_messages;

where

struct Message {
    static unsigned int s_last_id; // keep track of IDs to assign it automatically
    unsigned int id;
    string user_name;
    string content;
    string hour;

    Message(const string& a_user_name, const string& a_content) :
        user_name(a_user_name), content(a_content), id(++s_last_id), hour(currentDateTime())

    {
    }
    Message(){}

};

I want to read the file so that I can store the number into the id of the list, the word between "[@" and "]:" into the user_name, the next sentence into content and the date into the hour.

How can I do this?

Any help is appreciated

Thank you


Solution

  • The problem is: you are writing this file so it is easy to read by a person, while you should write it so it is easy to load by your program.

    You are using spaces to separate your elements, while spaces can very well happen inside those elements.

    I would suggest to use a symbol that is not likely to be used in the text, for example the pipe '|'. Also, I would write fixed-size elements first:

    18|2016-04-26.23:37:58|deniseeee|hello, how are you?

    Then you can read entire line, split it on those pipe symbols and load into your struct fields.