Существуют различные способы извлечения \ разбора даты и времени из формата даты, и вот что я бы сделал:
#include <tuple>
#include <sstream>
#define IS_LEAP_YEAR(year) ((year) % 4 == 0 && (year) % 100 != 0 || (year) % 100 == 0 && (year) % 400 == 0 || (year) % 400 == 0)
std::tuple<int, int, int> GiveDateFromFormat(std::string const& format, char const delimiter = '\\')
{
std::stringstream ss(format);
std::string date, month, year;
std::getline(ss, date, delimiter);
std::getline(ss, month, delimiter);
std::getline(ss, year, delimiter);
auto date_num = std::stoi(date), month_num = std::stoi(month), year_num = std::stoi(year);
if (month_num > 12 || month_num < 1 || date_num >(month_num % 2 == 0 && month_num != 2 ? 30 : 31) ||
date_num > (IS_LEAP_YEAR(year_num) ? 29 : 28) && month_num == 2)
throw std::invalid_argument("Date does not exist!");
return std::make_tuple(date_num, month_num, year_num);
}
Обратите внимание, что проверка даты только для того, чтобы убедиться, что она не требуется ...
Значительно сокращено, даже может быть:
std::tuple<int, int, int> GiveDateFromFormat(std::string const& format, char const delimiter = '\\')
{
std::stringstream ss(format);
std::string date, month, year;
std::getline(ss, date, delimiter);
std::getline(ss, month, delimiter);
std::getline(ss, year, delimiter);
return std::make_tuple(std::stoi(date), std::stoi(month), std::stoi(year));
}
Использование:
int main()
{
auto date_time = GiveDateFromFormat("29\\2\\2016");
std::cout << "Date: " << std::get<0>(date_time) << std::endl
<< "Month: " << std::get<1>(date_time) << std::endl
<< "Year: " << std::get<2>(date_time) << std::endl;
return 0;
}
Выход:
Дата: 29
Месяц: 2
Год: 2016