【发布时间】:2015-10-17 12:16:42
【问题描述】:
这段代码给出了一个输出:
在 Xcode 控制台中:2015-12-23 输出 date: Wed 2015-12-23
在 linux 终端上:2015-12-23 输出 2015-08-26(2015 年之前它只是一个空格)
谁能告诉我这怎么可能?我在打印日期时尝试了 puts() 方法,但也没有用。
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <time.h>
#include <string.h>
// Functions declaration
int StringLength(char *string);
bool IsDate (char myString[100], int length);
bool IsNumber (char myString[100], int length);
bool IsPrime (char myString[100]);
bool IsPalindrome (char myString[100], int length);
// Global variables declaration
int i;
int code;
bool tmp = true;
bool date = true;
char buffer[3];
int main(int argc, const char * argv[]) {
char unknownString[100];
printf("Insert a date string: ");
code = scanf("%100s", unknownString);
while (code == 1) {
date = IsDate(unknownString, strlen(unknownString));
printf("date: %s %s\n", buffer, unknownString);
printf("Insert a date string: ");
code = scanf("%100s", unknownString);
}
return 0;
}
bool IsDate (char myString[100], int length) {
tmp = true;
struct tm timeString;
// Only unknownString == 10 could be date because of the format DDDD-DD-DD which has 10 characters
if (length == 10) {
// Without this condition, IsDate would be true with format 1234x56x78
if (myString[4] == '-' && myString[7] == '-') {
timeString.tm_year = atoi(myString) - 1900;
timeString.tm_mon = atoi(&myString[5]) - 1;
timeString.tm_mday = atoi(&myString[8]);
timeString.tm_hour = 0;
timeString.tm_min = 0;
timeString.tm_sec = 1;
timeString.tm_isdst = 0;
if (mktime(&timeString) == -1) {
fprintf(stderr, "Unable to make time.\nError in IsDate function.\n");
exit(1);
}
else {
strftime(buffer, sizeof(buffer), "%c", &timeString);
}
}
else {
tmp = false;
}
}
// If length is different than 10
else {
tmp = false;
}
return tmp;
}
【问题讨论】:
-
为什么是 %99s?区别在哪里?
-
char buffer[3];是不是太小而无法通过strftime存储dd hh:mm:ss? -
您需要为字符串末尾的 NUL 终止符保留空间。
99告诉scanf最多读取 99 个字符,然后在字符串末尾附加\0。 -
但是我需要读取 100 个字符,所以 [0]-[99] 是一些字符,而 [100] 是 '\0'
-
如果是这样,使用大小为 101,而不是 100 的缓冲区。“[100] is '\0'” --
\0被写入无效内存如果使用的缓冲区大小为 100,则位于数组之后。因此使用大小为 101 的缓冲区来解决此问题。