将两个日期作为 C 中的 char 数组进行比较
Comparing two dates as char arrays in C
请耐心等待,这是我的第二个 Whosebug 问题,如果我做错了,请指出正确的方向
我有两个日期作为字符。
我打印日期:
printf("%s - %s\n",tmpPtr->date, currentDate);
而且我有一个 if 语句 总是 执行
if(tmpPtr->date != currentDate) { // perhaps strcmp(), don't know
printf("Dates are not equal\n");
}
但这不可能是真的,因为这些是我的结果:
27/12/2015 - 27/12/2015
Dates are not equal
27/12/2015 - 27/12/2015
Dates are not equal
28/12/2015 - 27/12/2015
Dates are not equal
29/12/2015 - 28/12/2015
Dates are not equal
29/12/2015 - 29/12/2015
Dates are not equal
29/12/2015 - 29/12/2015
Dates are not equal
30/12/2015 - 29/12/2015
Dates are not equal
31/12/2015 - 30/12/2015
Dates are not equal
31/12/2015 - 31/12/2015
Dates are not equal
这不可能是真的,因为有些日期是相等的?
我是否正确地比较了字符串?它只是比较内存分配还是类似的东西?
为了比较字符串,像这样使用 strcmp()
:
if (strcmp(tmpPtr->date,currentDate) != 0) {
printf("Dates are not equal\n");
}
如果日期的格式似乎与此相同,则使用 strcmp
。否则解析它们并将一个字符串的年、月和日期与另一个字符串的相应字段进行比较。
请耐心等待,这是我的第二个 Whosebug 问题,如果我做错了,请指出正确的方向
我有两个日期作为字符。
我打印日期:
printf("%s - %s\n",tmpPtr->date, currentDate);
而且我有一个 if 语句 总是 执行
if(tmpPtr->date != currentDate) { // perhaps strcmp(), don't know
printf("Dates are not equal\n");
}
但这不可能是真的,因为这些是我的结果:
27/12/2015 - 27/12/2015
Dates are not equal
27/12/2015 - 27/12/2015
Dates are not equal
28/12/2015 - 27/12/2015
Dates are not equal
29/12/2015 - 28/12/2015
Dates are not equal
29/12/2015 - 29/12/2015
Dates are not equal
29/12/2015 - 29/12/2015
Dates are not equal
30/12/2015 - 29/12/2015
Dates are not equal
31/12/2015 - 30/12/2015
Dates are not equal
31/12/2015 - 31/12/2015
Dates are not equal
这不可能是真的,因为有些日期是相等的?
我是否正确地比较了字符串?它只是比较内存分配还是类似的东西?
为了比较字符串,像这样使用 strcmp()
:
if (strcmp(tmpPtr->date,currentDate) != 0) {
printf("Dates are not equal\n");
}
如果日期的格式似乎与此相同,则使用 strcmp
。否则解析它们并将一个字符串的年、月和日期与另一个字符串的相应字段进行比较。