简体   繁体   English

C ++ Unicode问题

[英]C++ Unicode Issue

I'm having a bit of trouble with handling unicode conversions. 我在处理unicode转换时遇到麻烦。

The following code outputs this into my text file. 以下代码将其输出到我的文本文件中。 HELLO??O HELLO ?? O

std::string test = "HELLO"; 
std::string output;
int len = WideCharToMultiByte(CP_OEMCP, 0, (LPCWSTR)test.c_str(), -1, NULL, 0, NULL, NULL);
char *buf = new char[len];
int len2 = WideCharToMultiByte(CP_OEMCP, 0, (LPCWSTR)test.c_str(), -1, buf, len, NULL, NULL);
output = buf;
std::wofstream outfile5("C:\\temp\\log11.txt");
outfile5 << test.c_str();
outfile5 << output.c_str();
outfile5.close();

But as you can see, output is just a unicode conversion from the test variable. 但是正如您所看到的,输出只是来自测试变量的Unicode转换。 How is this possible? 这怎么可能?

Check if the LEN is correct after first measuring call. 第一次测量呼叫后,检查LEN是否正确。 In general, you should not cast test.c_str() to LPCWSTR. 通常,不应将test.c_str()强制转换为LPCWSTR。 The 'test' as is 'char'-string not 'wchar_t'-wstring. 'test'是'char'-string而不是'wchar_t'-wstring。 You may cast it to LPCSTR - note the 'W' missing. 您可以将其转换为LPCSTR-注意缺少“ W”。 The WinAPI has distinction between that. WinAPI之间有区别。 You really should be using wstring if you want to keep widechars in it.. Yeah, after re-reading your code, the test should be a wstring, then you can cast it to LPCWSTR safely. 如果您想在其中保留宽字符,则确实应该使用wstring 。是的,重新读取代码后, test应该是wstring,然后可以将其安全地转换为LPCWSTR。

after reading this Microsoft wstring reference 阅读此Microsoft wstring参考之后

I changed 我变了

std::string test = "HELLO";

to

std::wstring test = L"HELLO";

And the string was outputted correctly and I got 字符串输出正确,我得到了

HELLOHELLO 你好你好

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM