我正在开发一个测试代码,其中一个要求是检查文本是否包含以下格式的日期和时间。
DD / MM / YYYY HH:MM
我完全迷失了如何做到这一点
有人能指出我正确的方向吗?
我唯一的想法是逐一分析字符串中的每个字符,但这似乎很长,但必须有一个简短的方法?
if (pos != string::npos)
{
mystring=mystring.erase (0,13);
{
int z=0;
if (isalpha(mystring[0])) z+1;
cout << z << endl;
if (isalpha(mystring[1])) z+1;
if (isalpha(mystring[3])) z+1;
if (isalpha(mystring[4])) z+1;
if (isalpha(mystring[6])) z+1;
if (isalpha(mystring[7])) z+1;
if (isalpha(mystring[8])) z+1;
if (isalpha(mystring[9])) z+1;
if (isalpha(mystring[11])) z+1;
if (isalpha(mystring[12])) z+1;
if (isalpha(mystring[14])) z+1;
if (isalpha(mystring[15])) z+1;
if (mystring[0] > 3) z+1;
cout << z << endl;
if (mystring[3] > 1) z+1;
if (mystring[6] != 2) z+1;
if (mystring[7] != 0) z+1;
if (mystring[8] != 1) z+1;
if (mystring[9] != 4) z+1;
if (mystring[11] > 2) z+1;
if (mystring[14] > 6) z+1;
cout << mystring << "\n" << z << endl;
if (z != 0 ) {cout << "Please enter a valid Date & Time" << endl;}
}
}
为什么这是错的? :(
答案 0 :(得分:0)
在C中你可以使用 sscanf ,这是一个例子:
int main(int argc, char* argv[])
{
const char* buffer = "05/11/1996 13:24";
int day, month, year;
int hour, minute;
if(sscanf(buffer, "%2d/%2d/%4d %d:%d",
&month,
&day,
&year,
&hour,
&minute) == 5)
{
printf("parsed: DAY %d MONTH %d YEAR %d HOUR %d MINUTE %d\n", day, month, year, hour, minute);
// do further validations
}
else
{
printf("parse error, string do not contain valid date-time\n");
}
}