Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/61.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 字符数组指针返回不正确(当前年份ctime)_C++_C_Arrays_Datetime_Pointers - Fatal编程技术网

C++ 字符数组指针返回不正确(当前年份ctime)

C++ 字符数组指针返回不正确(当前年份ctime),c++,c,arrays,datetime,pointers,C++,C,Arrays,Datetime,Pointers,此函数 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] = '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] = '\0';

    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(表示零的ASCII码)将其转换为字符。然后整数将正确转换为字符。

'1'!=1
你看到区别了吗?
'1'
1
是不同的值。为了解决这个问题,只需添加
'0'
,我该怎么办?此(字符)((时间->tm_year+1900)%100)/10?感谢您的帮助!您无需知道
'0'
的代码(ASCII或其他代码)即可进行添加。谢谢您提供的信息。我不知道。我过去常常搜索字符的ASCII码。