Xcode和终端中的不同输出

时间:2015-10-17 12:16:42

标签: c terminal

此代码提供输出:

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;
}

1 个答案:

答案 0 :(得分:1)

缓冲区buffer对于语言环境的适当日期和时间表示而言太短。使此缓冲区至少为32个字节。

char buffer[32];

我相信您在Xcode中发现了一个错误,此代码:

strftime(buffer, sizeof(buffer), "%c", &timeString);

永远不应在Wed中生成buffer。它应该像在终端中那样生成任何内容,或者将名称剪切为2个字符We。如果您只对工作日缩写感兴趣,请将缓冲区设置为至少4个字节并使用格式"%a"