【问题标题】:Show current time on output window in Visual Studio 2013 using C使用 C 在 Visual Studio 2013 的输出窗口中显示当前时间
【发布时间】:2017-08-22 20:22:33
【问题描述】:

我正在尝试在 Visual Studio 的输出窗口上显示当前时间。我需要它来进行调试。由于 printf() 输出不会打印到 Visual Studio 的输出窗口,我需要使用 OutputDebugString()。

代码编译正确,但输出不正确。有人可以帮我吗?谢谢!

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));

Visual Studio 的输出窗口打印:

?‹???????]

预期:日期和时间打印正确。

【问题讨论】:

  • 尝试OutputDebugStringA 而不是OutputDebugString 并在此处报告是否有效。
  • 谢谢...它的工作原理..

标签: c


【解决方案1】:

我知道,Michael 的评论已经解决了您的问题。但是,您应该知道问题的原因,以免将来再次犯同样的错误。所以,这个答案总结了这一点。

首先,一些基础知识:: AWOutputDebugStringAOutputDebugStringW中分别代表AnsiWide characters

Ansi 字符占用 1 个字节的内存,例如 charWide 字符占用 2 个字节的内存,例如 wchar_t

更多参考可以看这里::Difference between char* and wchar_t*

现在,当您已经将 buff 定义为 char 时,为什么还要将其类型转换为 LPCWSTR。有关LPCWSTR 的更多参考,请参阅此::What does LPCWSTR stand for and how should it be handled with?

所以,基本上,你应该打电话给OutputDebugStringA(buff)

另一种解决方案是,将buff 定义为宽字符数组,

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);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-11
    • 2013-12-10
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多