首页 文章

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

提问于
浏览
0

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

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

我担心第一个''被用在一个字符串中(因为它可能表示连接)是它在括号中是否意味着加法?虽然我认为问题是在另一行,因为编译器在我给出的最后一行给出了错误 .

1 回答

  • 8

    在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库,它具有稍微好一点的语法 .

    希望这可以帮助!

相关问题