【发布时间】:2012-03-08 10:33:58
【问题描述】:
我的函数 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
};
如果错误代码来自 WSAGetLastError() 那么我必须使用 FormatMessage 将错误字符串作为 LPWSTR 获取,然后将其转换为 char*,我找到了这个页面:
How do I convert from LPCTSTR to std::string?
并尝试了这个显然适用于 LPCTSTR 的灵魂
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();
但它似乎不适用于 LPWSTR,结果总是“???????????”而且我对字符编码的理解还不够,无法找到解决方案。
任何人都可以对此有所了解吗?谢谢。
【问题讨论】:
-
LPTSTR 更改为 LPWSTR 或 LPSTR,具体取决于项目设置中的字符编码。如果您的 FormatMessage 是 FormatMessageW 的宏,您不能使用 wstring 代替 string 吗?
标签: c++ string character-encoding