1

我正在尝试使用当前时间和日期创建一个字符串

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;

我得到错误

初始化 'std::basic_string<_CharT, _Traits, _Alloc>::basic_string(const _CharT*, const _Alloc&) [with _CharT = char, _Traits = std::char_traits, _Alloc = std::allocator]' 的参数 1

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

4

1 回答 1

9

在 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();

Alternatively, consider using the Boost.Format library, which has slightly nicer syntax.

Hope this helps!

于 2012-08-27T20:27:18.107 回答