字符数组指针返回错误(当前年份和时间)

Char Array Pointer Returns Incorrect (Current Year ctime)

本文关键字:时间 指针 数组 返回 错误 字符      更新时间:2023-10-16

此函数

char *uniqid()
{
    static char uniqid[13];
    time_t curTime = time(0);
    struct tm *time = gmtime(&curTime);
    //Year
    uniqid[0] = '1';
    uniqid[1] = '5';
    uniqid[2] = 'n';
    return uniqid;
}

在cout中调用时返回"15",这通常是应该的,但是当我这样做时

char *uniqid()
{
    static char uniqid[13];
    time_t curTime = time(0);
    struct tm *time = gmtime(&curTime);
    //Year
    uniqid[0] = ((time->tm_year + 1900) % 100) / 10;
    uniqid[1] = ((time->tm_year + 1900) % 100) % 10;
    uniqid[2] = '';
    return uniqid;
}
当在cout中调用

时,它返回奇怪的图标。

'1'1是不同的值

1得到'1',只需加上'0'

uniqid[0] = ((time->tm_year + 1900) % 100) / 10;
uniqid[0] += '0';
uniqid[1] = (((time->tm_year + 1900) % 100) % 10) + '0';

tm_year为右整型。你将int类型赋值给char。这就产生了那个奇怪的图标。您需要通过添加48(表示0的ASCII码)将其转换为char。