• Unicode下的CString与char *转换


    在VS2005及以上的环境中,所见工程的默认字符集形式是Unicode,而VC6.0中,字符集形式为多字节字符集(MBCS: Multi-Byte Character Set),这样导致了许多字符转换的方法在Unicode的环境中不允许使用,强制类型转换的结果也会变得非常奇怪。

    如LPCTSTR与Char *的转换,在ANSI(VC6.0环境下默认编码)下,LPCTSTR == const char*

    但在Unicode下,LPCTSTR == const TCHAR*

    如果觉得转换麻烦的话,可以直接在新建工程时不选用Unicode Libraries,或者工程中修改 Project->Property->Configuration Properties->General->Project Defaults->Character Set,改为Use Multi-Byte Character Set。(此界面 alt+F7可以直接打开)

    问题就是,如果开发到一半,修改其中的默认编码方式,程序会变得相当奇怪,而且,有很多字符串常量需要去掉"_T()",所以,还是有必要记下Unicode中CString到Char *的转换方法的。

    方法1:使用API:WideCharToMultiByte进行转换(使用过,有效)

    CString str= CString("This is an example!");

    int n = str.GetLength(); //按字符计算,str的长度

    int len = WideCharToMultiByte(CP_ACP,0,str,n,NULL,0,NULL,NULL);//按Byte计算str长度

    char *pChStr = new char[len+1];//按字节为单位

    WideCharToMultiByte(CP_ACP,0,str,n,pChStr,len,NULL,NULL);//宽字节转换为多字节编码

    pChStr[len] = '';\不要忽略末尾结束标志

    //用完了记得delete []pChStr,防止内存泄露

    方法2:使用函数:T2A,W2A(未尝试)

    CString str= CString("This is an example!");

    USES_CONVERSION//声明标示符

    //调用函数,T2A和W2A均支持ATL和MFC中字符转换

    char *pChStr = T2A(str);

    //char *pChStr = W2A(str);//也可以实现转换

    注意:有时候需要包含头文件 #include <afxpriv.h>

    详细的内容参考:http://wenku.baidu.com/view/cb061a1352d380eb62946d68.html

    顺便记一下各种类型转为CString的方法:

    CString str = CString("This is an example!");

    CString str = _T("This is an ")+"an example";

    int x = 9;CString str; str.Format(_T("%d"), x);

    double x=9.7, CString str; str.Format(_T("%.3f"),x);

    转载自:

    http://blog.sina.com.cn/s/blog_63106cd80100yq8n.html

  • 相关阅读:
    lesson
    lesson
    课后习题-5
    lesson
    lesson
    lesson
    重启网络服务时 Bringing up interface eth0
    课后习题-4
    基础扩展
    课后习题-3
  • 原文地址:https://www.cnblogs.com/roea1/p/14696511.html
Copyright © 2020-2023  润新知