从字符转换为 TCHAR 中获得奇怪的字符
Getting weird characters from conversion of char to TCHAR
我从转换中得到了非常奇怪的字符。知道为什么吗?我从外部设备获取"数据",我需要将其显示在win32 GUI上。当我没有问题时
printf("%sn",data);
在控制台模式下,但在将其迁移到 Win32 时遇到问题,这需要我转换为 TCHAR 才能显示。
CHAR data[256];
TCHAR data1[256];
MultiByteToWideChar(CP_ACP,MB_COMPOSITE,data,-1,data1,0);
CreateWindow(TEXT("STATIC"), data1, WS_VISIBLE | WS_CHILD |
10, 50,300,300,hWnd, (HMENU) none, NULL, NULL);
顺便说一下,使用
hDLL=LoadLibrary("MyKad.dll");
在Win32中无法工作,所以我不得不使用
hDLL=LoadLibrary(TEXT("MyKad.dll"));
我可以知道这是对的吗?谢谢
代码失败的原因是您在 MultiByteToWideChar
的最后一个参数中传递了0
。您可以通过传递长度来修复代码,如果data1
:
MultiByteToWideChar(CP_ACP, MB_COMPOSITE, data, -1, data1, 256);
另请注意,在调用 API 函数时应检查错误。如果你这样做了,你会发现MultiByteToWideChar
失败了。
我使用以下函数转换为 UTF-16:
std::wstring MultiByteStringToWideString(const std::string& MultiByte,
const UINT CodePage)
{
std::wstring result;
int cchWideChar = MultiByteToWideChar(CodePage, 0, MultiByte.c_str(), -1,
NULL, 0);
if (cchWideChar > 0)
{
wchar_t* bufferW = new wchar_t[cchWideChar];
if (MultiByteToWideChar(CodePage, 0, MultiByte.c_str(), -1, bufferW,
cchWideChar) != 0)
{
result = std::wstring(bufferW);
}
delete[] bufferW;
}
return result;
}
因此,您可以按如下方式使用它:
std::wstring windowName = MultiByteStringToWideString(data, CP_ACP);
CreateWindow(L"STATIC", windowName.c_str(), ...);
相关文章:
- 从矢量<无符号字符>转换为字符* 包括垃圾数据
- 尝试将字符串/字符转换为整数会产生意外结果
- 如何使用C++将字符串中的字符转换为整数变量
- 字符转换功能 std::isupper() & std::islower() C++17
- 将字符 * 转换为字符串 *
- 在编译时将常量字符* 转换为常量 char_type*
- 如何在 C/C++ 中将无符号字符*转换为无符号字符数组?
- 错误:请求从"常量字符 [5]"转换为非标量类型"字符串"
- 无法使用字符串流将字符转换为字符串C++
- 将无符号字符 C++ 转换为 C#
- C++:使用没有位移位的指针将无符号字符转换为无符号 int
- 为什么我可以隐式地将字符*转换为常量字符*,但不能将无符号字符*
- 无法<string>从"常量字符 []"转换为<类名>
- 不能将字符转换为整数吗?
- 编译时将字符*转换为字节
- CP1251:从字符* 转换为 wchar_t* 时的编码失真
- 将单个字符转换为 std::string 前缀 \x01
- PPM 将字符转换为 int 授予负数
- 通过像printf这样的可变参数函数传递一个带有常量字符*转换函数的类
- 将常量字符* 转换为字符时出错