0

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();
outfile5.close();

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

ST3
  • 8,826
  • 3
  • 68
  • 92
jacobsgriffith
  • 1,448
  • 13
  • 18
  • 5
    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 01:07
  • Your comment and the link helped me understand it.. do you think you can help me out with a related issue here? http://stackoverflow.com/questions/15078661/trouble-getting-footage-path-after-effects-sdk – jacobsgriffith Feb 27 '13 at 01:11
  • Read Windows Unicode section in http://utf8everywhere.org. – Pavel Radzivilovsky Feb 27 '13 at 10:51

2 Answers2

1

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.

quetzalcoatl
  • 32,194
  • 8
  • 68
  • 107
0

after reading this Microsoft wstring reference

I changed

std::string test = "HELLO";

to

std::wstring test = L"HELLO";

And the string was outputted correctly and I got

HELLOHELLO

jacobsgriffith
  • 1,448
  • 13
  • 18