C ++从文件读取和存储信息 [英] C++ Reading and storing information from file

查看:146
本文介绍了C ++从文件读取和存储信息的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个文本文件,其中包含用于简单的进入/退出系统的以下数据:

I have a text file that has the following data for a simple entry/exit system:

其中每行都有{time_stamp} {name} {door_entry} {状态}

where each line has {time_stamp} {name} {door_entry} {status}

时间戳-自某个任意开始时间以来的秒数

time_stamp - number of seconds since some arbitrary start time

名称-工人用户名

door_entry -输入/退出的门号

状态-他们是进入还是退出门

status - whether they entered or exited the door

文本文件很大,大约有10,000个与此

The text file is large and has about 10,000 entries similar to this

问题:我想知道如何分解每一行并将每一条信息拆分为一个变量。例如,我在这里有Worker类:​​

Question: I'm wondering how I can decompose each line and split each piece of information into a variable. So for example I have the Worker class here:

class Worker
{
    std::string staffToken;
    int doorEntry;
    std::string status;
    public:
        Employee();
};

我也想用数组解决这个问题。我知道我可以使用Vector或Map,但是我想用数组来解决这个问题。
我为Worker类创建了一个指针对象数组。

I want to solve this problem with an array as well. I know I could use a Vector or a Map but I want to solve this with an array. I've created an array of pointer objects for the Worker class.

   typedef Worker * WorkPtr;
        WorkPtr * workers = new WorkPtr[MAX]; //where max is some large constant
        for (int i = 0; i < MAX; ++i)  
        {
        workers[i] = new Worker();
        }

我创建此问题的目的是我只想检查对于此文本文件中工人连续进入或退出多次的任何异常活动:

The goal of this problem I've created is that I simply want to check for any unusual activity in this text file where a Worker has entered or exited multiple times in a row:

推荐答案

模板以特定的定界符分割字符串

you can use this template to split a string with a certain delimiter

template<typename Out>
void split(const std::string &s, char delim, Out result) {
    std::stringstream ss;
    ss.str(s);
    std::string item;
    while (std::getline(ss, item, delim)) {
        *(result++) = item;
    }
}

std::vector<std::string> split(const std::string &s, char delim) {
    std::vector<std::string> elems;
    split(s, delim, std::back_inserter(elems));
    return elems;
}

例如:

ifstream fin("your_file");
while(getline(fin,str))
{
    vector<string> res;
    res = split(str, ' ');
    //your process with res
}

这篇关于C ++从文件读取和存储信息的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆