我可以写一个函数来解析字符串日期,但我觉得我在这里重新发明了轮子。是否有更快的,也许内置于 C++ 的方法来从这种格式的字符串日期:1/4/2000 到更易于使用的 int,如 20000104?
最佳答案
除非您还需要内置的 C++ 方法来进行验证,否则“显而易见的”解析是:
int parseDate(const std::string &input) {
int month;
int day;
int year;
if (std::sscanf(input.c_str(), "%d/%d/%d", &month, &day, &year) != 3) {
// handle error
} else {
// check values to avoid int overflow if you can be bothered
return 10000 * year + 100 * month + day;
}
}
如果您希望编写多行代码类型安全,您可以使用流提取器而不是sscanf
。
标准库中肯定没有任何东西可以为您完成 10000 * year + 100 * month + day
。如果您不拘泥于那个确切的值,您只是想要一个顺序正确的整数,那么您可以查看您的平台是否具有告诉您所谓的“儒略日”的功能。
关于C++ 将字符串日期 (1/4/2000) 转换为整数日期 (20000104),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14580471/