【问题标题】:Argument of type "const char *" is incompatible with parameter of type "LPCWSTR" Visual Studio 2019“const char *”类型的参数与“LPCWSTR”Visual Studio 2019 类型的参数不兼容
【发布时间】:2020-12-05 21:07:52
【问题描述】:

我是 Windows 上 C/C++ 编码的新手,在运行我的代码时遇到了这个错误。之前有人问了一个类似的问题,我将在下面链接,但是,这个解决方案对我不起作用,因为我没有更改我的字符集的选项。

argument of type const char* is incompatible with parameter of type "LPCWSTR"

这是我的代码的样子。

#include <Windows.h>

INT CALLBACK WinMain(HINSTANCE hInstance, HINSTANCE hPrevInstance,
    PSTR lpCmdLine, INT nCmdShow)
{

    OutputDebugString("Lets test this out \n");

    return 0;
}

【问题讨论】:

  • 你试过OutputDebugString(L"Lets test this out \n");吗?请注意使用 w 版本的std::wstring 和 I/O 类 (wostream)。
  • 或者调用OutputDebugStringA,考虑到正在传递的字符串以及OutputDebugStringW的工作原理,这似乎是首选路由。
  • @πάνταῥεῖ 成功了!谢谢!我对此有点陌生,但 L 是什么意思?
  • @User9123 宽字符串字面量。

标签: c++ windows visual-studio


【解决方案1】:

有两种方法可以解决此问题。

首先是使用由宽字符组成的字符串:

OutputDebugString(L"Lets test this out \n");
//                ^

其次是调用带窄字符串的函数版本:

OutputDebugStringA("Lets test this out \n");
//               ^

由于 Windows API 更喜欢使用宽字符串,我更喜欢第一种解决方案。

附: LPCWSTR 代表“指向常量宽字符串的长指针”。 L 已过时,您可以忽略它。

【讨论】:

  • 第三种方法 - 使用 TEXT() 宏:OutputDebugString(TEXT(“Let’s test this out \n”));,它确保字符串文字以 OutputDebugString()(不带 A 或 W 后缀)所期望的方式编码。
  • @RemyLebeau TEXT()_T() 宏在人们从 Ansi 过渡到 Unicode API 时很有用。今天我会说,如果它们没有过时,它们应该是过时的。除非问题上下文很明显需要它,否则我不会建议它。
  • 使用基于 TCHAR 的 API 通常已过时。直接使用OutputDebugStringAoutputDebugStringW 是最好的,但如果OP 决定坚持使用OutputDebugString,那么应该使用TEXT() 来匹配。
  • 只是扩展上面Mark所说的,用错误替换所有功能,最后用A,它会完美运行。
  • @Triangle4 我在这个答案中实际上给出了 两个 解决方案,您强调了第二个;但更好的是第一个。当然,在这些函数名称中添加 W 也没有什么坏处。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-08-28
  • 1970-01-01
  • 2019-12-16
  • 2016-05-19
  • 1970-01-01
  • 2020-01-20
相关资源
最近更新 更多