Parsing yyyy-MM-dd HH: mm: ss date time string?

I have a date 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 an easier way than running it via stringstream for each component? (without support for boost or C ++ 11).

thank

+4
source share
1 answer

sscanf()probably the easiest option. This is a feature of the C library, so purists may reject 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 C ++ 11 regex , which would make for more robust parsing of the string.

+7
source

Source: https://habr.com/ru/post/1544074/


All Articles