I want to parse the various time elements from a string. The input
string has the ff format:
'YYYY-MM-DD HH:MM:SS AM'
Can anyone show me how to do this?
This is the only way that I know of that don't require any extra
libraries/extensions:
#include <iostream>
#include <sstream>
#include <string>
template <class T>
T stoa(const std::string& s)
{
T t;
std::istringstream iss(s);
if (!(iss >> t))
throw "Can't convert";
return t;
}
int main()
{
std::string input;
std::getline(std::cin, input);
int year, mon, day, hour, min, sec;
year = stoa<int>(input.substr(0, 4));
mon = stoa<int>(input.substr(5, 2));
day = stoa<int>(input.substr(8, 2));
hour = stoa<int>(input.substr(11, 2));
min = stoa<int>(input.substr(14, 2));
sec = stoa<int>(input.substr(17, 2));
if (input.substr(20, 2) == "PM")
hour += 12;
}
Don't forget to apply error checking