【问题标题】:Different outputs in Xcode and terminalXcode 和终端中的不同输出
【发布时间】: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 的缓冲区来解决此问题。

标签: c terminal


【解决方案1】:

缓冲区 buffer 对于区域设置的适当日期和时间表示来说太短了。使此缓冲区至少为 32 个字节。

char buffer[32];

我相信你在 Xcode 中发现了一个错误,这段代码:

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

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

【讨论】:

    猜你喜欢
    • 2017-12-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-12-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多