问题
I have a text file that has the following data for a simple entry/exit system:
where each line has {time_stamp} {name} {door_entry} {status}
time_stamp - number of seconds since some arbitrary start time
name - The workers username
door_entry - door number entered/exited
status - whether they entered or exited the door
The text file is large and has about 10,000 entries similar to this
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();
};
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:
回答1:
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;
}
for example:
ifstream fin("your_file");
while(getline(fin,str))
{
vector<string> res;
res = split(str, ' ');
//your process with res
}
来源:https://stackoverflow.com/questions/45807690/c-reading-and-storing-information-from-file