将文本文件读入结构

Reading a text file into an structure

我正在尝试从 .txt 文件中读取一些信息,然后将其存储在一个结构中,但我不知道该怎么做,只能选择我需要的词。

.txt 如下

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

.txt 中的一行如下所示:

18 [@deniseeee]:你好,你好吗? 2016-04-26.23:37:58

所以,问题是我有一个结构列表

list<Message*> g_messages;

哪里

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(){}

};

我要读取文件以便我可以将数字存入列表的id,“[@”和“]:”之间的单词存入user_name,下一句存入内容和日期到小时。

我该怎么做?

感谢任何帮助

谢谢

问题是:你写这个文件是为了让人容易阅读,而你应该写它是为了让你的程序容易加载。

您正在使用空格分隔元素,而空格很可能出现在这些元素内部。

我建议使用不太可能在文本中使用的符号,例如竖线“|”。另外,我会先写固定大小的元素:

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

然后您可以读取整行,将其拆分为那些管道符号并加载到您的结构字段中。