gpt4 book ai didi

c++ - 创建包含 time_t 的字符串时出错?

转载 作者:塔克拉玛干 更新时间:2023-11-03 08:27:43 25 4
gpt4 key购买 nike

我正在尝试创建一个包含当前时间和日期的字符串

time_t t = time(NULL); //get time passed since UNIX epoc
struct tm *currentTime = localtime(&t);
string rightNow = (currentTime->tm_year + 1900) + '-'
+ (currentTime->tm_mon + 1) + '-'
+ currentTime->tm_mday + ' '
+ currentTime->tm_hour + ':'
+ currentTime->tm_min + ':'
+ currentTime->tm_sec;

我得到了错误

initializing argument 1 of 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]'|

我担心字符串中使用的第一个“+”(因为它可能表示串联)是因为它在括号中意味着加法吗?虽然我认为问题出在不同的行,因为编译器在我给出的最后一行给出了错误。

最佳答案

在 C++ 中,您不能使用 + 运算符连接数字、字符和字符串。要以这种方式连接字符串,请考虑使用 stringstream:

time_t t = time(NULL); //get time passed since UNIX epoc
struct tm *currentTime = localtime(&t);
ostringstream builder;
builder << (currentTime->tm_year + 1900) << '-'
<< (currentTime->tm_mon + 1) << '-'
<< currentTime->tm_mday << ' '
<< currentTime->tm_hour << ':'
<< currentTime->tm_min << ':'
<< currentTime->tm_sec;
string rightNow = builder.str();

或者,考虑使用 Boost.Format库,它的语法稍微好一些。

希望这对您有所帮助!

关于c++ - 创建包含 time_t 的字符串时出错?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12149063/

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