views:

180

answers:

3

I am developing a MFC program under windows CE. It is unicode by default. I can use TRACE to print some message like this

TRACE(TEXT("Hey! we got a problem!\n"));

It works fine if everything is unicode. But however, I got some ascii string to print. For example:

// open the serial port
m_Context = CreateFile(TEXT("COM1:"), ...);
int rc = ReadFile(m_Context, buffer, 1, cBytes, NULL);
// Oops!! We got a problem, because we can't print a non-unicode string
TRACE(TEXT("Read data: %s\n"), buffer);

I read string through com1 from a GPS module. It send text like this "$GPSGGA,1,2,3,4". They are all encoded with ASCII. I want to print them out with TRACE, how can I do?

Thanks.

A: 

It should work as long as the text retrieved is really ASCII in the 0–127 range, and the Unicode encoding is UTF-8. Unicode has adopted the lower ASCII range, using the same code points.

Joó Ádám
+3  A: 

Use "%hs" to format a narrow string argument, provided that you don't care about the code page. See, for example, this page for description of format specifiers.

atzz
+1  A: 

In Windows the "%S" format specifier (capital 'S') will format a string that's the 'opposite' of the build. In UNICODE builds it'll expect an ANSI/MBCS string and in non-UNICODE builds it'll expect a UNICODE argument.

I'm not 100% sure this will work on CE, but the following works on the desktop (for a UNICODE build):

TRACE( TEXT("Unicode string: \"%s\", ASCII string: \"%S\""), L"unicode", "ascii");
Michael Burr