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
|
#include <string>
#include <sstream>
#include <iostream>
#include <vector>
#include <stdexcept>
#include <algorithm>
#include <exception>
using namespace std;
vector<int> Date::getDateFromString(string str)
{
// holds extracted date
std::vector<int> date;
// holds validation list
std::vector<char> valid = { '1', '2', '3', '4', '5', '6', '7', '8', '9', '0' };
// sample to work with (day, month of year)
std::istringstream ss(str);
// ignore dots
while (std::getline(ss, str, '.'))
{
// temporary
string temp = str;
// doing validation here, accepting only numbers
for (const auto& ref : str)
if (std::find(valid.begin(), valid.end(), ref) == valid.end())
throw std::invalid_argument("date is not valid");
else if (ref == '0' && str.size() == 2)
{
// remove zero if found
std::size_t pos = temp.find('0');
temp.erase(pos, pos);
}
// if OK convert to integer and store day, month and year
int num = std::atoi(str.c_str());
date.push_back(num);
}
return date;
}
// TEST CASE
int main() try
{
// try to screw up this date to see exception
std::string date("21.5.2020");
auto result = Date::getDateFromString(date);
// show result, integers (day, month and year)
for (const auto& ref : result)
{
std::cout << ref << std::endl;
}
}
catch (std::invalid_argument& ex)
{
// If invalid input exception is trhown and programs aborts
std::cout << ex.what() << std::endl;
}
|