【问题标题】:cannot convert 'LPCWSTR {aka const wchar_t*}' to 'const char*' for argument '1' to 'int printf(const char*, ...)'无法将参数 '1' 的 'LPCWSTR {aka const wchar_t*}' 转换为 'const char*' 到 'int printf(const char*, ...)'
【发布时间】:2020-04-04 08:53:03
【问题描述】:

在过去的四五年里,我从未尝试过用 C 编码,所以我不知道如何解决这个问题。

我的代码是这样的:

char szExePath[MAX_PATH]; //
//"C:\\Program Files (x86)\\Application Verifier\\vrfauto.dll"
printf("Please input the execution file path:\n");
scanf("%s", szExePath);
//char LPCWSTR
WCHAR wsz[64];
swprintf(wsz, L"%S", szExePath);
LPCWSTR m_szFilename = wsz;

setlocale(LC_ALL, "chs");
_tprintf(m_szFilename);

【问题讨论】:

  • 这是 C,不是 C++
  • 欢迎来到 Stack Overflow _ 正如@CinCout 所建议的,您应该用“C”正确标记您的过去。另外,我刚刚在 Google 上搜索了您的问题的标题,并找到了 4-5 个已经存在的 SO 答案……您也应该这样做,以防其中一个对您有所帮助。

标签: c char wchar


【解决方案1】:

根据您的项目配置,TCHAR 映射到 char 时,_tprintf() 映射到 printf(),或者 wchar_t 映射到 wprintf()。显然,您的项目设置为将TCHAR 映射到char,这就是为什么您在将wchar_t* 传递给printf() 时遇到错误的原因。

但是,您显示的代码没有使用TCHAR,因此您根本不应该使用_tprintf()m_szFilename 明确是 wchar_t[],所以直接使用 wprintf() 代替:

wprintf(m_szFilename);

另外,考虑使用wscanf() 将输入读取为wchar_t[],而不是使用中间char[]

WCHAR szExePath[MAX_PATH]; //
//L"C:\\Program Files (x86)\\Application Verifier\\vrfauto.dll"
printf("Please input the execution file path:\n");
wscanf(L"%259s", szExePath);

setlocale(LC_ALL, "chs");
wprintf(szExePath);

但是请注意,无论您使用scanf() 还是wscanf(),读取都会在空白处停止,因此如果用户输入类似"C:\Program Files (x86)\Application Verifier\vrfauto.dll" 的路径,您的缓冲区将只接收"C:\Program。考虑到这一点,您需要改用gets()/_getws()(或更安全的gets_s()/_getws_s())或fgets()/fgetws()

【讨论】:

  • getsgets_s 都不鼓励使用,请使用 fgets/fgetws
猜你喜欢
  • 2017-03-31
  • 1970-01-01
  • 2013-08-11
  • 2014-03-02
  • 1970-01-01
  • 1970-01-01
  • 2015-08-05
  • 1970-01-01
  • 2016-07-06
相关资源
最近更新 更多