I have a date time that comes from mysql. I need to extract each part:
int year;
int month;
int day;
int hour;
int min;
int sec;
example:
2014-06-10 20:05:57
Is there a simpler way than running it through stringstream for each component? (no boost or c++11 solutions please).
Thanks
sscanf()
is probably the most straightforward option. It is a C library function, so purists might disapprove it.
Here is an example:
int year;
int month;
int day;
int hour;
int min;
int sec;
const char * str = "2014-06-10 20:05:57";
if (sscanf(str, "%d-%d-%d %d:%d:%d", &year, &month, &day, &hour, &min, &sec) == 6)
{
// sscanf() returns the number of elements scanned, so 6 means the string had all 6 elements.
// Else it was probably malformed.
}
And here is a live test.
Another nice solution would also be to use a C++11 regex which would make for a more robust parsing of the string.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With