【问题标题】:CString format with Unicode returns wrong character带有 Unicode 的 CString 格式返回错误的字符
【发布时间】:2011-07-11 23:19:37
【问题描述】:

我正在尝试使用以下代码格式化 CString:

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

然而,实际上 str 的值不是“μ”,而是设置为“¼”。当我调试它时,它会将 wch 识别为“μ”。

此外,如果我这样做:

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

它给出值为“¼”的str。 (它似乎没有出现,但 ¼ 之后应该有一个上标 L。)

编译器设置为使用 unicode,因为在程序中我可以调用 _T() 并让它正确评估,而不是在格式化 CString 时。

我做错了什么?

*编辑:* 进行更多调试表明 CString Format 方法的 arglist 接收到的值为“Ü_”

【问题讨论】:

  • 您是否可能误解了您所看到的内容? UNICODE 字符 μ 是 0x03BC。将其解释为两个单字节字符,您会得到¼,即 0xBC 和上标 L,即 0x03。
  • 您是否使用 UNICODE 和 _UNICODE 编译您的应用程序?您的源文件是保存为 ANSI 还是 UTF-8?您是否尝试过显式使用 CStringW?

标签: c++ mfc


【解决方案1】:

我相信您需要使用“长”字符或字符串格式说明符——所以%lc 用于wchar_t%ls%S 用于字符串。

【讨论】:

  • 这似乎没有帮助。使用%lc 给我一个空字符串,%ls%S 抛出一个错误
  • @jonbooz :他的建议是正确的,并且适用于 VC++ 2010。您可能需要发布更多代码...
【解决方案2】:

试试

setlocale(LC_ALL, "");

在调用 Format 之前。 (除非您正在做任何不寻常的事情,否则在您的应用程序开始附近调用一次 setlocale 就足够了。)

【讨论】:

    【解决方案3】:

    我看到 Miu%c%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;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-04-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多