开发者

How to concatenate strings in the function m_stream in C++?

I'm writing a logger for my program in C++.

I have this piece of code:

void Log::Write(char* logline)
{
    time_t rawtime;
    stru开发者_高级运维ct tm * timeinfo;
    time ( &rawtime );
    timeinfo = localtime ( &rawtime );
    m_stream << asctime (timeinfo) << logline << endl;
}

This is a log

Tue Oct 11 13:07:28 2011

I want a different output on a single line like this: Tue Oct 11 13:07:28 2011 - This is a log

How can I do it? Thank you!


As it said in docs:

The string result produced by asctime contains exactly 26 characters and has the form Wed Jan 02 02:03:55 1980\n\0

So if you don't want to write line ending symbol you could use use 'write' function specifying exact amount of characters to write like this

time_t rawtime;
struct tm * timeinfo;
time ( &rawtime );
timeinfo = localtime ( &rawtime );
m_stream.write( asctime (timeinfo), 24 );
m_stream << " - " << logline << std::endl;

Of course in that case you should write comment explaining why '24' is used...


Your problem is asctime():

http://www.cplusplus.com/reference/clibrary/ctime/asctime/

The string is followed by a new-line character ('\n') and the terminating null-character.

As the returned string is a C string, you could replace the \n with a \0:

char * str = asctime(timeinfo);
str[strlen(str) - 1] = '\0';

AS long as you don't call ctime or asctime again, the content won't be overwritten.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜