1

I am trying to display current time on output window of Visual Studio. I need it for debugging purpose. Since printf() output doesn't print to output window of Visual Studio, i need to use OutputDebugString().

Code compiles correctly but output doesn't come out correctly. Can someone help me out here ? Thanks !

char buff[100];
time_t rawtime;
struct tm * timeinfo;
time(&rawtime);
timeinfo = localtime(&rawtime);

sprintf(buff, "[%d %d %d %d:%d:%d]", timeinfo->tm_mday, timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, timeinfo->tm_min, timeinfo->tm_sec);
OutputDebugString(LPCWSTR(buff));

OUTPUT Window of Visual Studio prints :

?‹???????]

Expected: Date and time is printed correctly.

LPs
  • 16,045
  • 8
  • 30
  • 61
Sunny
  • 11
  • 1

1 Answers1

0

I know, the comment from Michael has already solved your problem. But, you should know the cause of problem to avoid making the same mistake again in future. So, this answer summarizes that.

First of all, some basics:: A and W in OutputDebugStringA & OutputDebugStringW, respectively stands for Ansi and Wide characters.

Ansi chars take upto 1 byte of memory like char and Wide chars take 2 bytes of memory like wchar_t.

For more reference, you can look here:: Difference between char* and wchar_t*

Now, when you have already defined buff as char, then why are you type-casting it to LPCWSTR. For more reference on LPCWSTR, see this:: What does LPCWSTR stand for and how should it be handled with?

So, basically, you should be calling OutputDebugStringA(buff).

Another solution is, define buff as wide char array,

wchar_t buff[100];
wsprintf(buff, L"[%d %d %d %d:%d:%d]", timeinfo->tm_mday, 
     timeinfo->tm_mon + 1, timeinfo->tm_year + 1900, timeinfo->tm_hour, 
     timeinfo->tm_min, timeinfo->tm_sec);
OutputDebugStringW(buff);
Community
  • 1
  • 1
Abhineet
  • 5,320
  • 1
  • 25
  • 43