non*_*ble 3 c++ command-line-arguments
我正在开发一个带有两个命令行参数的程序.两个参数都应该是yyyy-mm-dd形式的日期.由于其他人将使用此程序并且它将从mysql请求,我想确保命令行参数有效.我最初的想法是循环传入字符串的每个元素并对其执行某种测试.' - '很容易检查,但我不太确定如何处理数字,并在int和chars之间区分它们.另外,我需要第一个日期是"小于或等于"第二个,但我很确定我可以处理它.
如果您可以使用boost库,您可以这样简单地执行:
string date("2015-11-12");
string format("%Y-%m-%d");
date parsedDate = parser.parse_date(date, format, svp);
Run Code Online (Sandbox Code Playgroud)
你可以在这里阅读更多相关信息.
如果您想要纯C++解决方案,可以尝试使用
struct tm tm;
std::string s("2015-11-123");
if (strptime(s.c_str(), "%Y-%m-%d", &tm))
std::cout << "Validate date" << std::endl;
else
std::cout << "Invalid date" << std::endl;
Run Code Online (Sandbox Code Playgroud)
此外,您可以进行简单的检查以查看日期是否有效,而不是例如2351-20-35.一个简单的解决方案是:
bool isleapyear(unsigned short year){
return (!(year%4) && (year%100) || !(year%400));
}
//1 valid, 0 invalid
bool valid_date(unsigned short year,unsigned short month,unsigned short day){
unsigned short monthlen[]={31,28,31,30,31,30,31,31,30,31,30,31};
if (!year || !month || !day || month>12)
return 0;
if (isleapyear(year) && month==2)
monthlen[1]++;
if (day>monthlen[month-1])
return 0;
return 1;
}
Run Code Online (Sandbox Code Playgroud)
资料来源:http://www.cplusplus.com/forum/general/3094/