gpt4 book ai didi

c++ - 从 char 转换为 string 时丢失编码

转载 作者:行者123 更新时间:2023-11-30 02:34:40 24 4
gpt4 key购买 nike

我在 Ubuntu 中为一个 C++ 项目使用 Codeblocks。我有以下用于创建时间戳的函数:

char *myclass::getCurrentTime() {

time_t rawtime;
struct tm * timeinfo;
char buffer[30];

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

strftime(buffer, 30, "%d-%m-%YT%H:%M:%S.000+02:00", timeinfo);
return buffer;
}

当我通过以下方式将返回的字符转换为字符串时:

char *curr_time = getCurrentTime();
string time_str = string(curr_time);

它丢失了编码,如果我尝试将字符串写入文件或打印它,我会得到未定义的字符。如果我使用 char,则编码没有问题。当我在 Win7 中使用 Visual Studio 时一切正常。

最佳答案

您正在返回一个悬挂指针。在 get CurrentTime 返回后,数组 buffer 被销毁,但您仍然使用指向它的指针。这是未定义的行为 - 它有时似乎有效,但没有任何保证。

如果您在 getCurrentTime 中转换为 string 并返回它,那么一切都会好起来的 - string 的部分要点是为您解决此类问题。

关于c++ - 从 char 转换为 string 时丢失编码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34392242/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com