简体   繁体   English

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

[英]Error creating a string containing a time_t?

I'm trying to create a string with the current time and date 我正在尝试使用当前时间和日期创建一个字符串

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;

I get the error 我得到错误

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]'| 初始化'std :: basic_string <_CharT,_Traits,_Alloc> :: basic_string(const _CharT *,const _Alloc&)[]的参数1,其中_CharT = char,_Traits = std :: char_traits,_Alloc = std :: allocator]'|

I'm worried about the first '+' being used in a string (as it may denote concatenation) is the fact that it is in brackets make it mean addition? 我担心在字符串中使用第一个“ +”(因为它可能表示串联)是因为它放在方括号中意味着加法? Though I think the problem is in a different line, as the compiler gives the error at the last line I gave. 尽管我认为问题出在另一行,但编译器在我给出的最后一行给出了错误。

In C++, you cannot concatenate numbers, characters, and strings by using the + operator. 在C ++中,不能使用+运算符来连接数字,字符和字符串。 To concatenate strings this way, consider using a stringstream : 要以这种方式连接字符串,请考虑使用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();

Alternatively, consider using the Boost.Format library, which has slightly nicer syntax. 或者,考虑使用Boost.Format库,该库的语法稍好。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM