jonbooz
jonbooz

Reputation: 37

CString format with Unicode returns wrong character

I'm trying to format a CString using the following code:

const wchar_t * wch = L"μ";
CString str;
str.Format(_T("%c"), wch[0]);

However, instead of str having the value of "μ" it actually is set to "¼". When I debug it, it recognizes wch as "μ".

Further, if I do:

const wchar_t * wch = L"μ";
CString str;
str.Format(_T("%s"), wch);

it gives str with value "¼". (It doesn't seem to show up but there should be a superscript L after the ¼.)

The compiler is set to use unicode, as else where in the program I am able to call _T() and have it evaluate correctly, just not when formatting a CString.

What am I doing wrong?

*Edit: * Doing more debugging shows that the CString Format method's arglist receives a value of "Ü_"

Upvotes: 1

Views: 9206

Answers (3)

Windows programmer
Windows programmer

Reputation: 8065

Try

setlocale(LC_ALL, "");

before calling Format. (Unless you're doing anything unusual, it's enough to call setlocale once near the beginning of your application.)

Upvotes: 1

Ulterior
Ulterior

Reputation: 2892

I see Miu with %c and with %lc

// a1.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <afx.h>

int _tmain(int argc, _TCHAR* argv[])
{
    const wchar_t * wch = L"μ";
    CString str;
    str.Format(_T("%c"), wch[0]);
    MessageBox( GetForegroundWindow(), str.GetBuffer(), L"MyChar", MB_OK + MB_ICONHAND );
    str.Format(_T("%s"), wch);
    MessageBox( GetForegroundWindow(), str.GetBuffer(), L"MyChar", MB_OK + MB_ICONHAND );
    return 0;
}

Upvotes: 0

QuantumMechanic
QuantumMechanic

Reputation: 13946

I believe you need to use a "long" char or string format specifier -- so %lc for the wchar_t and %ls or %S for the string.

Upvotes: 4

Related Questions