放在这格式有点难看
#include
#include
#include
using namespace std;
class Date
{
public:
unsigned year;
unsigned month;
unsigned day;
Date(string s);
void show(){
cout<<month<<"月"<<day<<"日"<<year<<"年"<<endl;
};
};
Date::Date(string s){
string number="1234567890/";
string came=",";
string _month;
unsigned pos,pos1,pos2,pos3;
unsigned _pos,_pos1,_pos2;
int flag=0;
if((pos=s.find_first_not_of(number))==string::npos){
flag=1;
}
if((pos=s.find_first_of(came)!=string::npos)){
flag=2;
}
switch(flag){
case 2://首先处理January 1,1900 格式
pos1=0;
pos1=s.find_first_of(number);
_month=s.substr(0,pos1);
if (_month == "January ") month = 1;
if (_month == "April ") month = 4;
if (_month == "May ") month = 5;
if (_month == "June ") month = 6;
if (_month == "July ") month = 7;
if (_month == "August ") month = 8;
if (_month == "September ") month = 9;
if (_month == "October ") month = 10;
if (_month == "November ") month = 11;
if (_month == "December ") month = 12;
pos2=pos1++;
pos1=s.find_first_of(came,pos1);
day=stoul(s.substr(pos2-1,pos1));
pos3=pos1++;
year=stoul(s.substr(pos3,s.size()-1));
break;
case 1:
//处理1/1/1900数据
_pos=0;
_pos=s.find_first_of("/",_pos);
month=stoul(s.substr(0,_pos));
_pos1=++_pos;
_pos=s.find_first_of("/",_pos1);
day=stoul(s.substr(_pos1,_pos));
_pos2=_pos++;
year=stoul(s.substr(_pos2,s.size()-1));
break;
case 0:
//处理Jan 1 1900数据
_pos=0;
_pos=s.find_first_of(number);
_month=s.substr(0,_pos);
if (_month == "Jan ") month = 1;
if (_month == "Feb ") month = 2;
if (_month == "Mar ") month = 3;
if (_month == "Apr ") month = 4;
if (_month == "May ") month = 5;
if (_month == "Jun ") month = 6;
if (_month == "Jul ") month = 7;
if (_month == "Aug ") month = 8;
if (_month == "Sep ") month = 9;
if (_month == "Oct ") month = 10;
if (_month == "Nov ") month = 11;
if (_month == "Dec ") month = 12;
_pos1=_pos++;
_pos=s.find_first_of(number,_pos);
day=stoul(s.substr(_pos1-1,_pos));
year=stoul(s.substr(_pos,s.size()-1));
break;
}
}
int main(){
Date _today("1/1/1900");
_today.show();
return 0;
}
//只想尝试输出一个,但不行
获取子字符串时偏移量不对:
case 1分支里
year = stoul(s.substr(_pos2, s.size() - 1));
应为:
year = stoul(s.substr(_pos2+1, s.size() - 1));
case 2和case 0分支没细看,你可以再检查下。
运行是这个样子
case 1分支里
year = stoul(s.substr(_pos2, s.size() - 1));
应为:
year = stoul(s.substr(_pos2+1, 4));
运行结果
case 1里的天和年的子串获取都有问题,帮你改了一下
case 1:
//处理1/1/1900数据
_pos=0;
_pos1=s.find_first_of("/");//找到第一个“/”的位置,_pos1值为1
month=stoul(s.substr(0,_pos1));
++_pos1;
_pos2=s.find_last_of("/");//找到最后一个“/”的位置_pos1值为3
day=stoul(s.substr(_pos1,(_pos2-_pos1)));
++_pos2;
year=stoul(s.substr(_pos2,4));
break;