1. 程式人生 > >primer C++ 9.5.5練習 9.5.1題

primer C++ 9.5.5練習 9.5.1題

9.5.1  :設計日期類 通過傳入string初始化類成員。

寫了挺長時間,儘量運用了近幾章所學,作為複習題很有效果。

/*****************
primerC++ practice 9.5.5-9.51
   narcissu,2018
****************/
/* date.h
*/
#ifndef DATE_H
#define DATE_H
#include <iostream>
#include <string>
#include <vector>
#include <sstream>
class Date {
private:
	unsigned long year{ 0 },
		month{ 0 },
		day{ 0 };
	std::vector<std::string> vstr{ "january","february","march","april","may","june","july","august","september","october","november","december" };//查詢詞源
	std::string vstr2{"1234567890"};//所有數字
public:
	Date() = default;//預設建構函式
	Date(std::string inps);//目標建構函式
};
#endif
Date::Date(std::string inps) {
	std::transform(inps.begin(), inps.end(), inps.begin(), ::tolower);//大小寫轉換
	int index = 0;
	string::size_type sindex;
	for (auto decl : vstr) {//迴圈搜尋月份單詞 若找到則將查詢次數存入month作為月份並移除單詞及後一位字元 
		if ((sindex = inps.find(decl) )!= string::npos) {
			month = index + 1;
			inps.erase(sindex, decl.size()+1);
			break;
		}
		++index;
	}
	if (index == 12) {//若不存在月份單詞則將第一個特殊符號位之前的部分轉換成ul型別存入month
		index = inps.find_first_not_of(vstr2);
		string ds(inps, 0,index);
		month = std::stoul(ds);
		inps.erase(0, index+1);
	}
	index = 0;
        //處理剩餘部分,運用isstream以空格為間隔符讀取並轉換為ul型別數存入對應類成員
	while ((index = inps.find_first_not_of(vstr2,index)) != string::npos) {
		inps.erase(index, 1);
		inps.insert(index, " ");
		index += 1;
	}
	std::istringstream oss(inps);
	std::string str1, str2;
	oss >> str1 >> str2;
	day = std::stoul(str1);
	year = std::stoul(str2);
	cout << month << " "  << day << " " << year<<endl;//輸出以測試結果
}


/*
progmain.cpp
main()主函式部分 其他省略
*/
int main(int argc, char *argv[]) {
	Date d1("12/12/1988");//直接傳參
	system("pause");
	return EXIT_SUCCESS;
}