如何获取整数作为字符串

How to get an integer as a string

我正在尝试 return 一个字符串,它是年份。

此代码不在我的 GUI 层附近,因此我正在尝试以下操作

#define COMPANY_COPYRIGHT            "Copyright © " + getYear() + "; 

当它被调用时我有

void getCopyRight(BSTR* copyRight) 
{
    CString CopyRightStr    =   (CString)COMPANY_COPYRIGHT;
}

我正在努力使用 getYear() 函数

#include <time.h>

const char getYear()
{
    time_t rawtime;
    struct tm * timeinfo;

    time (&rawtime);
    timeinfo = localtime (&rawtime);

    int year = timeinfo->tm_year + 1900;

    char buf[8];               //I think 8 as I expect only 4 characters, each is 2 bit

    sprintf(buf,"%d", year);   //I can see year shows 2015. But not sure why it's %d because this should be the output format, surely it should be %s but this errors

    return buf;                //I can see buf shows 2015
}

以上错误与

'return' : cannot convert from 'char[4] to 'const char'

我理解错误信息,但不知道该怎么做。如果我加一个cast,比如

    return (const char)buf;                //I can see buf shows 2015

然后它似乎 return 单个 ASCII 字符,这不是我想要的。

我想要的是,而不是 return 将 2015 作为 int,它 return 只是值“2015”作为 'string'...

撇开任何其他问题,您的代码至少会生成 undefined behaviour

在您的 getYear() 函数中,您试图 return 局部变量的地址 buf。这是不可能的。

相反,您可以

  • 定义bufchar指针。
  • 使用malloc()/calloc()
  • 动态分配内存
  • 使用 return buf 来自 getYear()
  • 在调用者中使用 returned 指针。

也就是说,如果我理解正确你的问题,你可以利用 strtol() 字符串 转换为 int .您还需要更改函数签名。


编辑:

好的,关于转换部分我弄错了,你想要的是将一个int转换成一个字符串。你最好的选择是 sprintf()