Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 将LPWSTR转换为char*/string_C++_String_Character Encoding - Fatal编程技术网

C++ 将LPWSTR转换为char*/string

C++ 将LPWSTR转换为char*/string,c++,string,character-encoding,C++,String,Character Encoding,向我的函数GetErrorString()传递了一个错误代码,该错误代码可能是WSAGetLastError()的结果,也可能是在我的DLL中定义的一个错误代码,当对我的DLL函数的调用无法完成时返回 我有一个std::pairs数组,它存储我的错误代码以及它们的const char*错误字符串 std::pair<int, const char*> errorCodeArray[12] = { std::pair<int,char*>(0,"Success")

向我的函数GetErrorString()传递了一个错误代码,该错误代码可能是WSAGetLastError()的结果,也可能是在我的DLL中定义的一个错误代码,当对我的DLL函数的调用无法完成时返回

我有一个std::pairs数组,它存储我的错误代码以及它们的const char*错误字符串

std::pair<int, const char*> errorCodeArray[12] =
{ 
    std::pair<int,char*>(0,"Success"),
    std::pair<int,char*>(1,"Connection Error"),
    std::pair<int,char*>(2,"Request Timed Out"),
    // ..etc
};
但它似乎不适用于LPWSTR,结果总是“????????”而且我对字符编码的理解还不足以找到解决方案

有人能解释一下吗?谢谢。

提供两种功能:

  • FormatMessageA()
  • FormateMessageW()
显式使用
FormatMessageA()
,以避免转换的必要性

虽然这并不能直接回答这个问题,但它提供了一种解决方案,消除了从
LPWSTR
转换为
char*

的要求,提供了两种功能:

  • FormatMessageA()
  • FormateMessageW()
显式使用
FormatMessageA()
,以避免转换的必要性


虽然这并不能直接回答问题,它提供了一种解决方案,通过删除从
LPWSTR
转换为
char*
的要求,您可能需要查看wcstombs函数以将其转换为您可能需要查看wcstombs函数以将其转换为LPWSTR或LPSTR,具体取决于项目设置中的字符编码。如果您的FormatMessage是FormatMessageW的宏,您不能使用wstring而不是string吗?根据项目设置中的字符编码,LPTSTR将更改为LPWSTR或LPSTR。如果您的FormatMessage是FormatMessageW的宏,您不能使用wstring而不是string吗?感谢hmjd,它比我试图使其更精确的简单得多,*a函数是围绕*W函数的包装,使用默认代码页为您进行转换。所以,从某种意义上说,这是一个直接的答案。感谢hmjd,它比我想说的要简单得多。准确地说,*a函数是围绕着*W函数的包装,它使用默认代码页为您进行转换。所以,从某种意义上说,这是一个直接的答案。
int size = WideCharToMultiByte(CP_ACP, 0, errCode, -1, 0, 0, NULL, NULL);
char* buf = new char[size];
WideCharToMultiByte(CP_ACP, 0, errCode, -1, buf, size, NULL, NULL);
std::string str(buf);
delete[] buf;
return str.c_str();