1
votes

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]'|

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.

1

1 Answers

9
votes

In C++, you cannot concatenate numbers, characters, and strings by using the + operator. To concatenate strings this way, consider using a 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!