Take the 2-minute tour ×

I'm having a bit of trouble with handling unicode conversions.

The following code outputs this into my text file. 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();

But as you can see, output is just a unicode conversion from the test variable. How is this possible?

share|improve this question
Are you trying to understand why it doesn't work when you tell the compiler, "Trust me, I know it's a LPCWSTR." when it's not? –  chris Feb 27 '13 at 1:07
Your comment and the link helped me understand it.. do you think you can help me out with a related issue here? stackoverflow.com/questions/15078661/… –  user941632 Feb 27 '13 at 1:11
Read Windows Unicode section in utf8everywhere.org. –  Pavel Radzivilovsky Feb 27 '13 at 10:51
add comment

2 Answers

Check if the LEN is correct after first measuring call. In general, you should not cast test.c_str() to LPCWSTR. The 'test' as is 'char'-string not 'wchar_t'-wstring. You may cast it to LPCSTR - note the 'W' missing. The WinAPI has distinction between that. 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.

share|improve this answer
add comment

after reading this Microsoft wstring reference

I changed

std::string test = "HELLO";


std::wstring test = L"HELLO";

And the string was outputted correctly and I got


share|improve this answer
add comment

Your Answer


