Alternative to #define

Hi everyone,
In the program I am writing I need to include a time stamp which need to be in the form: "time: 2011-09-08 14:21:44.4730". I have achieved this by doing:

1
2
3
4
5
6
7
		GetLocalTime(&lt);
		timeStampStream.str("");
		timeStampStream <<lt.wYear<<"-"<< ::std::setfill('0')<< ::std::setw(2)<<lt.wMonth<<"-"
		  <<::std::setw(2)<<lt.wDay<<" "<< ::std::setw (2)<<lt.wHour<<":"<<::std::setw(2)<<lt.wMinute
		  <<":"<<::std::setw(2)<<lt.wSecond<<"."<<::std::setw(3)<<lt.wMilliseconds<<"0";
		timeStampString = timeStampStream.str();
		::std::cout << "time: " << timeStampString << ::std::endl;


I was thinking of using a #define like so
#define TIME_STAMP_INFO <<lt.wYear<<"-"<< ::std::setfill('0')<< ::std::setw(2)<<lt.wMonth<<"-"<<::std::setw(2)<<lt.wDay<<" "<< ::std::setw (2)<<lt.wHour<<":"<<::std::setw(2)<<lt.wMinute<<":"<<::std::setw(2)<<lt.wSecond<<"."<<::std::setw(3)<<lt.wMilliseconds<<"0"

then to do a time stamp each time I would type:

1
2
3
4
5
		GetLocalTime(&lt);
		timeStampStream.str("");
		timeStampStream TIME_STAMP_INFO;
		timeStampString = timeStampStream.str();
		::std::cout << "time: " << timeStampString << ::std::endl;


In C this is probably what I would have done, but I'm sure there is a better way to do it in C++. Normally you can use const in C++ where I had previously used #define in C, however I can't seem to work it out for this. Anybody have any ideas? Also is there anyway for a #define to continue onto another line? The statement would be about 250 characters long which is more than twice what I would like any of my lines of code to be.

And yes I have looked into the differences of #define and const etc. But I can't seem to find something on the internet that answers this problem. (Although I'm very possibly just searching for the wrong thing)

Thanks for your help,
Meerkat
Actually, to me it looks like you want a function.
Yea that makes much more sense. I was just so caught up in finding a way of doing it similar to a #define I wasn't thinking straight. Thanks.

Meerkat
Last edited on
Encase anybody is interested here's what the function looks like:

1
2
3
4
5
6
7
8
9
10
11
12
void timeStamp()
{
    SYSTEMTIME st, lt;
	::std::ostringstream timeStampStream;

	GetLocalTime(&lt);
	timeStampStream.str("");
	timeStampStream <<lt.wYear<<"-"<< ::std::setfill('0')<< ::std::setw(2)<<lt.wMonth<<"-"<<::std::setw(2)<<lt.wDay
	  <<" "<< ::std::setw (2)<<lt.wHour<<":"<<::std::setw(2)<<lt.wMinute<<":"<<::std::setw(2)<<lt.wSecond<<"."
	  <<::std::setw(3)<<lt.wMilliseconds<<"0";
	timeStampString = timeStampStream.str();
}


timeStampString is a std::string with global scope. Not much to it, but if anybody has any questions just ask.

Finally though does anybody know a better way to make a time stamp of this form?

Meerkat
Last edited on
Topic archived. No new replies allowed.