返回一个常量字符 *
Return a const char *
我写了一个返回当前日期的函数。在函数内部,我"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()
成员函数。
相关文章:
- 如何循环访问常量字符**?
- constexpr 函数获取常量字符*
- 如何计算常量字符**中的总字符数?
- QDial:如何将 int 值传递给需要常量字符*的 Qfile?
- 为什么 std::string_view 比常量字符*快?
- 函数签名与调用的函数不匹配,常量字符[]和字符*之间的区别?
- 在编译时将常量字符* 转换为常量 char_type*
- 将字符串数组传递给接受常量字符**的函数
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 字符串强制转换为常量字符*
- 使用常量字符*时退出代码 139
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法在声明时使用初始值设定项列表初始化常量字符*/字符串数组的向量
- 无法<string>从"常量字符 []"转换为<类名>
- 初始化常量字符* 数组
- 常量字符*的性质是什么?
- C++ 获取向量中常量字符* [ ] 的长度
- 无法将参数 1 从 WCHAR 转换为常量字符 *
- 如何在 c++ 中将向量转换为<string>常量字符* const*?
- C++将常量字符* 指针数组传递给对象