您的位置:首页 > 编程语言 > C语言/C++

C++ primer 第五版 中文版 练习 9.51 个人code

2014-09-04 16:00 513 查看
C++ primer 第五版 中文版 练习 9.51

题目:设计一个类,它有三个unsigned成员,分别表示年、月、日。为其编写构造函数,接受一个表示日期的string参数。

你的构造函数应该能处理不同的数据格式,如 January 1,1900、1/1/1900、Jan 1 1900 等。

答:以下代码只能针对本题给出的这三种格式来处理,由于本人智商略低……用最笨的办法来实现了本题的要求,仅能处理本题给出的三种格式,且没有把月份的英文形式转换成数字形式。

/*
设计一个类,它有三个unsigned成员,分别表示年、月、日。为其编写构造函数,接受一个表示日期的string参数。
你的构造函数应该能处理不同的数据格式,如 January 1,1900、1/1/1900、Jan 1 1900 等。
*/

#include <string>
#include <iostream>

using namespace std;

class MyDate
{
public:
MyDate() = default;
MyDate(const string &s)
{
string month, day, year;
string::size_type pos = 0, pos1 = 0;
auto iter = s.begin();
if ((pos = s.find_first_of("/")) != string::npos)
{
month.assign(iter, iter + pos);
pos1 = s.find_first_of("/", pos+1);
day.append(iter + pos+1, iter + pos1);
year.append(iter + pos1+1, s.end());
}
else if ((pos = s.find_first_of(",")) != string::npos)
{
pos= s.find(" ");
month.assign(iter, iter + pos);
pos1 = s.find_first_of(",");
day.assign(iter + pos + 1, iter + pos1);
year.assign(iter + pos1 + 1, s.end());
}
else if ((pos = s.find_first_of(",/")) == string::npos)
{
pos = s.find(" ");
month.assign(iter, iter + pos);
pos1 = s.find(' ', pos+1);
day.assign(iter + pos, iter + pos1);
year.assign(iter + pos1 + 1, s.end());
}
Year = stoi(year, 0);
Month = stoi(month, 0);
Day = stoi(day, 0);
}
~MyDate(){}
void display()
{
cout << Year << " "<<Month<<" " << Day;
}
private:
unsigned Year;
unsigned Month;
unsigned Day;
};

int main()
{
string str = "12/2/1990";
string str1 = "10 2,1990";
string str2 = "12 30 1990";
MyDate mydate(str);
MyDate mydate1(str1);
MyDate mydate2(str2);

mydate.display();
cout << endl;
mydate1.display();
cout << endl;
mydate2.display();
cout << endl;

return 0;

}


执行结果:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: