【发布时间】:2015-07-18 00:37:55
【问题描述】:
我正在尝试返回一个字符串,即年份。
此代码不在我的 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'
我了解错误消息,但不知道该怎么做。如果我添加演员表,例如
return (const char)buf; //I can see buf shows 2015
然后它似乎返回一个 ASCII 字符,这不是我想要的。
我想要的是,不是将 2015 作为 int 返回,而是仅将值“2015”作为“字符串”返回...
【问题讨论】:
-
如果这是 C,你的代码就毫无意义。你确定这不是 C++ 吗?考虑将该宏设为局部变量,或者如果不可能,至少将其设为适当的宏:
#define COMPANY_COPYRIGHT ( CString("Copyright © ") + getYear() )。 (假设C++,否则宏是废话) -
重复引用的是我正在做的事情!
-
存在多个问题:
char类型为单个字符,返回指向局部变量的指针无效,4不足以存储 4 个字符的字符串。我建议你读一本好的 C 书。 -
strptime,snprintf可能是有用的函数,一旦您纠正了未定义的行为问题。 -
您添加了一条评论我认为是 8,因为我预计只有 4 个字符,每个是 2 位。不,那不是真的,您至少需要
buf[5],因为C 字符串是空终止的。正如我所说,去读一本好的 C 书,值得花时间。