gpt4 book ai didi

c++ - 我如何让这个函数返回一个日期时间字符串

转载 作者:行者123 更新时间:2023-11-28 05:39:00 25 4
gpt4 key购买 nike

我有以下函数,在我的一生中我无法返回一个字符串:

void GetDateTimeString()
{
auto t1 = std::time(nullptr);
auto tm1 = *std::localtime(&t1);
stringstream dattim1;
cout << put_time(&tm1, "%Y-%m-%d_%H-%M-%S");
}

我已经试过了,但没有成功,导致程序崩溃:

std::string GetDateTimeString()
{
time_t t1 = std::time(nullptr);
tm tm1 = *std::localtime(&t1);
stringstream dattim1;
dattim1 << put_time(&tm1, "%Y-%m-%d_%H-%M-%S");
std::string returnValue = dattim1.str();
return returnValue;
}

最后我想这样调用它:

string dateString = GetDateTimeString();

我做错了什么?

最佳答案

您函数的第一个版本是 void 类型,因此它不会返回任何内容。 cout 将只打印时间,例如到控制台。

在第二个函数中,您尝试再次使用 put_time,但该函数不符合您的需求。而是使用 strftime 将时间复制到 char-array,然后复制到 string:

std::string GetDateTimeString()
{
time_t t1 = std::time(nullptr);
tm tm1 = *std::localtime(&t1);
char buffer[80];
strftime(buffer, sizeof(buffer), "%Y-%m-%d_%H-%M-%S", &tm1);
std::string returnValue(buffer);
return returnValue;
}

关于c++ - 我如何让这个函数返回一个日期时间字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37601793/

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