【问题标题】:argument of type char * parameter of type lpcwstrchar 类型的参数 * lpcwstr 类型的参数
【发布时间】:2015-02-25 02:52:19
【问题描述】:

我在 c++ 中收到错误“char 类型的参数 * lpcwstr 类型的参数”如何修复?

char text[MAX_PATH]= {};
sprintf(text, "Number of Words: %S", computerName);
sprintf(text, "Number of Sentences: %S", userName);
sprintf(text, "Number of Digits: %d", objSystemInfo.dwNumberOfProcessors);
sprintf(text, "Number of Upper Case: %d", bit);
MessageBox(NULL, text , L"Sistem Bilgisi", MB_OK);

【问题讨论】:

  • 您正在混合窄字符和宽字符串。将参数提供给 MessageBox() 时,您需要使用其中一个
  • @AhmetKorkusuz 另请注意,您的每个sprintf() 调用都不会添加到text,而是会覆盖当前内容!

标签: c++ winapi error-handling


【解决方案1】:

MessageBox 接收到 LPCWSTR,你可以将其表示为 wchar_t 而不是 char 并使用 wsprintf 写入 wchar_t,如下所示:

wchar_t text[MAX_PATH]= {};
wsprintf(text, L"Number of Words: %s", computerName);
wsprintf(text, L"Number of Sentences: %s", userName);
wsprintf(text, L"Number of Digits: %d", objSystemInfo.dwNumberOfProcessors);
wsprintf(text, L"Number of Upper Case: %d", bit);
MessageBox(NULL, text , L"Sistem Bilgisi", MB_OK);

【讨论】:

  • 从技术上讲,MessageBox() 接收 LPCTSTR,它是 LPCSTR (const char*) 或 LPCWSTR (const wchar_t*),具体取决于是否定义了 UNICODE。如果你想直接使用wchar_t,你需要直接调用MessageBoxW()
【解决方案2】:

请注意,LPCWSTR 在 winnt 标头中定义为: typedef const WCHAR* LPCWSTR 表示指向 const 宽字符的指针。 在您的情况下,文本是字符表。 MessageBox 的第二个参数必须是 LPCWSTR,以防您的项目使用 UNICODE。 因此,如果您尝试将char text[MAX_PATH]= {}; 的声明更改为wchar_t text[MAX_PATH]= {};,它将解决您的编译问题。 但是,您的 MessageBox 将显示一条空文本消息,如 cmets sprintf 中所述,不会向您的文本变量添加文本。

【讨论】:

  • 如果给定宽字符串,对sprintf 的调用将无法编译。
  • @JonathanPotter: sprintf() 在使用%S 说明符时接受宽字符串输入值(注意大写S)。
  • @JonathanPotter:是的,您必须使用基于char 的缓冲区。但是您可以传递宽字符串输入值,它们将在缓冲区格式化期间转换为 Ansi。这就是%S 的用途。同样,swprintf() - %S 将接受窄字符串作为输入,并在格式化 wchar_t 缓冲区期间将其转换为宽字符串。
  • @RemyLebeau:令人惊讶的是,我知道如何使用 wsprintf 等,我最初的评论是针对回答者,试图帮助他改进答案。
  • wsprintf() (Win32) 和 s(w)printf() (CRTL) 之间存在很大差异。 wsprintf() 只支持s(w)printf() 支持的一小部分选项。
【解决方案3】:

最简单的解决方案是调用MessageBoxA()

MessageBoxA(NULL, text, "Sistem Bilgisi", MB_OK);

否则,如果您继续调用MessageBox()TCHAR 版本,则需要更新您的代码以使用TCHAR 作为您的文本:

TCHAR text[MAX_PATH] = {};
_stprintf(text,
  _T("Computer Name: %ls\nUserName: %ls\nNumber of Processors: %u\nBit: %d"),
  computerName,
  userName,
  objSystemInfo.dwNumberOfProcessors,
  bit
);
MessageBox(NULL, text, TEXT("Sistem Bilgisi"), MB_OK);

否则,请调用MessageBox()WCHAR 版本并使用WCHAR 作为您的文本:

WCHAR text[MAX_PATH] = {};
swprintf(text,
  L"Computer Name: %ls\nUserName: %ls\nNumber of Processors: %u\nBit: %d",
  computerName,
  userName,
  objSystemInfo.dwNumberOfProcessors,
  bit
);
MessageBoxW(NULL, text, L"Sistem Bilgisi", MB_OK);

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-28
    • 1970-01-01
    相关资源
    最近更新 更多