[英]Parsing yyyy-MM-dd HH:mm:ss date time string?
I have a date time that comes from mysql. 我有一个来自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? 有没有比通过stringstream为每个组件运行它更简单的方法? (no boost or c++11 solutions please). (请不要使用boost或c ++ 11解决方案)。
Thanks 谢谢
sscanf()
is probably the most straightforward option. sscanf()
可能是最直接的选择。 It is a C library function, so purists might disapprove it. 它是一个C库函数,所以纯粹主义者可能不赞成它。
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. 另一个不错的解决方案也是使用C ++ 11正则表达式 ,这将使字符串更健壮的解析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.