forked from Mooophy/Cpp-Primer
-
Notifications
You must be signed in to change notification settings - Fork 2
/
ex9_51.cpp
89 lines (78 loc) · 2.48 KB
/
ex9_51.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
// @Soyn
//
// Exercise 9.51:
// Write a class that has three unsigned members representing year,
// month, and day. Write a constructor that takes a string representing
// a date. Your constructor should handle a variety of date formats,
// such as January 1, 1900, 1/1/1900, Jan 1, 1900, and so on.
//
#include <iostream>
#include <string>
#include <vector>
/*@Soyn
*Ex 9.51
*Date: 2015.6.12
*/
using namespace std;
class My_date{
private:
unsigned year, month, day;
public:
My_date(const string &s){
unsigned tag;
unsigned format;
format = tag = 0;
// 1/1/1900
if(s.find_first_of("/")!= string :: npos)
{
format = 0x01;
}
// January 1, 1900 or Jan 1, 1900
if((s.find_first_of(',') >= 4) && s.find_first_of(',')!= string :: npos){
format = 0x10;
}
else{ // Jan 1 1900
if(s.find_first_of(' ') >= 3
&& s.find_first_of(' ')!= string :: npos){
format = 0x10;
tag = 1;
}
}
switch(format){
case 0x01:
day = stoi(s.substr(0, s.find_first_of("/")));
month = stoi(s.substr(s.find_first_of("/") + 1, s.find_last_of("/")- s.find_first_of("/")));
year = stoi(s.substr(s.find_last_of("/") + 1, 4));
break;
case 0x10:
if( s.find("Jan") < s.size() ) month = 1;
if( s.find("Feb") < s.size() ) month = 2;
if( s.find("Mar") < s.size() ) month = 3;
if( s.find("Apr") < s.size() ) month = 4;
if( s.find("May") < s.size() ) month = 5;
if( s.find("Jun") < s.size() ) month = 6;
if( s.find("Jul") < s.size() ) month = 7;
if( s.find("Aug") < s.size() ) month = 8;
if( s.find("Sep") < s.size() ) month = 9;
if( s.find("Oct") < s.size() ) month =10;
if( s.find("Nov") < s.size() ) month =11;
if( s.find("Dec") < s.size() ) month =12;
char chr = ',';
if(tag == 1){
chr = ' ';
}
day = stoi(s.substr(s.find_first_of("123456789"), s.find_first_of(chr) - s.find_first_of("123456789")));
year = stoi(s.substr(s.find_last_of(' ') + 1, 4));
break;
}
}
void print(){
cout << "day:" << day << " " << "month: " << month << " " << "year: " << year;
}
};
int main()
{
My_date d("Jan 1 1900");
d.print();
return 0;
}