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码。