#include<iostream>
#include<string>
using namespace std;
string oops("0123456789");
class time{
public:
time(const string & ss);
friend void display(time & t);
private:
unsigned year;
unsigned month;
unsigned day;
};
time::time(const string & ss)
{
int biaozhi = 0;
if (ss.find(",") < string::npos)//若有,号
{
biaozhi = 0;
}
if (ss.find("/") != string::npos)
{
biaozhi = 1;
}
if (ss.find(",") == string::npos && ss.find("/") == string::npos)
{
biaozhi = 2;
}
switch (biaozhi){
case 0:
if (ss.find("Jan") != string::npos) month = 1;
if (ss.find("Feb") != string::npos) month = 2;
if (ss.find("Mar") != string::npos) month = 3;
if (ss.find("Apr") != string::npos) month = 4;
if (ss.find("May") != string::npos) month = 5;
if (ss.find("Jun") != string::npos) month = 6;
if (ss.find("Jul") != string::npos) month = 7;
if (ss.find("Aug") != string::npos) month = 8;
if (ss.find("Sep") != string::npos) month = 9;
if (ss.find("Oct") != string::npos) month = 10;
if (ss.find("Nov") != string::npos) month = 11;
if (ss.find("Dec") != string::npos) month = 12;
day = stoi(ss.substr(ss.find_first_of(oops), ss.find_first_of(",") - ss.find_first_of(oops)));
year = stoi(ss.substr(ss.find_first_of(",")+1));
break;
case 1:
month = stoi(ss.substr(0, ss.find_first_of("/")));
day = stoi(ss.substr(ss.find_first_of("/") + 1, ss.find_last_of("/") - ss.find_first_of("/")));
year = stoi(ss.substr(ss.find_last_of("/") + 1));
break;
case 2:
if (ss.find("Jan") != string::npos) month = 1;
if (ss.find("Feb") != string::npos) month = 2;
if (ss.find("Mar") != string::npos) month = 3;
if (ss.find("Apr") != string::npos) month = 4;
if (ss.find("May") != string::npos) month = 5;
if (ss.find("Jun") != string::npos) month = 6;
if (ss.find("Jul") != string::npos) month = 7;
if (ss.find("Aug") != string::npos) month = 8;
if (ss.find("Sep") != string::npos) month = 9;
if (ss.find("Oct") != string::npos) month = 10;
if (ss.find("Nov") != string::npos) month = 11;
if (ss.find("Dec") != string::npos) month = 12;
day = stoi(ss.substr(ss.find_first_of(oops), ss.find_last_of(" ") - ss.find_first_of(oops)));
year = stoi(ss.substr(ss.find_last_of(" ") + 1));
break;
}
}
void display(time & t)
{
cout << t.year<< "年" << t.month << "月" << t.day <<"日"<< endl;
}
int main(void)
{
time time1("January 4,1205");
display(time1);
time time2("1/2/1900");
display(time2);
time time3("Feb 3 1900");
display(time3);
}C++ Primer 课后练习9.51
最新推荐文章于 2023-10-13 17:51:08 发布
本文介绍了一个简单的日期解析器实现,该解析器能够根据不同的日期格式(如包含月份名称的完整格式、斜杠分隔的数字格式等)解析并转换为统一的年月日格式。通过几个具体的例子展示了如何使用这个解析器。
33万+

被折叠的 条评论
为什么被折叠?



