我有以下函数,在我的一生中我无法返回一个字符串:
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/