这是我的结构:
struct Event{
int day;
int month;
int year;
int weekday;
string event;
};
我的事件数据文件应该是这样的:
# Comment and empty lines are ignored
# ’$’ means LAST, ’*’ is wildcard
# Weekday on symbolic from Mon,Tue,Wed,Thu,Fri,Sat,Sun
# Events specs start
# Last day is payday
$.*.*:*:Payday
# Birthday at 1.3
1.3.*:*:Birthday Party
# Darts on Fridays
*.*.*:Fri:Darts evening
13.*.*:Fri:Friday the 13th
# EOF
我试着写了这个函数:
void readFile(vector<string> &data){
string line;
ifstream readFile("events.dat", ios::in);
if (!readFile) {
cerr<<"File COuld not be opened"<<endl;
exit(EXIT_FAILURE);
}
while (readFile && !readFile.eof()) {
getline(readFile,line);
if (line.length() == 0 or line[0] == '#' or line[0] == '/')
break;
data.push_back(line);
}
}
但现在我不知道如何将数据 vector 转换为事件 vector ?
最佳答案
你可以用 std::istringstream
和 std::getline
来完成,它有第三个参数是一个 char
它应该停止消耗字符并返回字符串。另一种方法是使用正则表达式,下面是一种使用正则表达式解析它的方法,我只用一个字符串对其进行了测试,但它应该让你开始如何去做。
http://coliru.stacked-crooked.com/a/d3aed577b2f72bd7
#include <iostream>
#include <string>
#include <regex>
struct Event{
int day;
int month;
int year;
int weekday;
std::string event;
};
int main()
{
std::regex pattern("([0-9\\$\\*]+)\\.([0-9\\$\\*]+)\\.([0-9\\$\\*]+):(\\w+):([\\w ]+)" );
std::string line = "13.*.*:Fri:Friday the 13th";
std::smatch sm;
Event evt;
if (std::regex_match(line, sm, pattern)) {
std::string val1 = sm[1];
if (val1 == "*")
evt.day = -1; // wildcard
else if (val1 == "$")
evt.day = -2; // last
else
evt.day = std::stoi(val1);
val1 = sm[2];
if (val1 == "*")
evt.month = -1; // wildcard
else if (val1 == "$")
evt.month = -2; // last
else
evt.month = std::stoi(val1);
val1 = sm[3];
if (val1 == "*")
evt.year = -1; // wildcard
else if (val1 == "$")
evt.year = -2; // last
else
evt.year = std::stoi(val1);
std::string weekDay = sm[4];
std::vector<std::string> weekdays = {"Mon", "Tue", "Wen", "Thr", "Fri", "Sat", "Sun"};
auto it = std::find(weekdays.begin(), weekdays.end(), weekDay);
evt.weekday = std::distance(weekdays.begin(), it);
evt.event = sm[5];
std::cout << evt.day << ", " << evt.month << ", " << evt.year << ", " << evt.weekday << ", " << evt.event << "\n";
}
}
关于输出:
13, -1, -1, 4, Friday the 13th
关于c++ - 如何将文件中的数据导入我的结构数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37072352/