返回一个常量字符 *

Return a const char *

本文关键字:常量 字符 一个 返回      更新时间:2023-10-16

我写了一个返回当前日期的函数。在函数内部,我"cout"结果并且它有效,但是当我"cout"函数时,它不起作用。我得到了垃圾。

const char* engineCS::getDate() const
{
    time_t t = time(0);
    struct tm *now = localtime(&t);
    char buf[20];
    strftime(buf, sizeof(buf), "%Y-%m-%d %X", now);
    cout << buf << endl;
    return buf;
}

示例 :内部 : 2012-02-02 00:00:00外面:?????抗体

怎么了?类似的问题:函数和返回常量字符*

感谢

编辑:现在怎么了?对不起,我做得太多了 VB.NET...

const char* engineCS::getDate() const
{
    time_t t = time(0);
    struct tm *now = localtime(&t);
    char *buf;
    buf = new char[20];
    strftime(buf, sizeof(buf), "%Y-%m-%d %X", now);
    cout << buf << endl;
    return buf;
}

更改函数以返回 std::string ,一切都会好起来的。除了返回类型之外,您无需进行任何进一步的更改。如果使用者需要原始char const *,请对生成的字符串调用 c_str() 成员函数。