使用 Unicode 字符集:char数组和CString类型如何相互转换

解决方案 »

  1.   

    CString str = L"12中文329d";
    int len = WideCharToMultiByte( CP_ACP , 0 , str , str.GetLength() , NULL , 0 , NULL , NULL );
    char* pAscii =new char[len+1];
    len = WideCharToMultiByte(  CP_ACP , 0 , str , str.GetLength() , pAscii , len +1 , NULL ,NULL );
    pAscii[len] = 0;
      

  2.   

    CString str = L"12中文329d";
    int len = WideCharToMultiByte( CP_ACP , 0 , str , str.GetLength() , NULL , 0 , NULL , NULL );
    char* pAscii =new char[len+1];
    len = WideCharToMultiByte( CP_ACP , 0 , str , str.GetLength() , pAscii , len +1 , NULL ,NULL );
    pAscii[len] = 0;
    //////////////////////////////////////////////
    const char* pAscii = "12中文329d";
    CString str;
    int len = MultiByteToWideChar( CP_ACP, 0 , pAscii , strlen( pAscii ) , 0 , 0 );
    len = MultiByteToWideChar( CP_ACP, 0 , pAscii , strlen( pAscii ) , str.GetBuffer(len+1) , len+1 );

    str.ReleaseBuffer( len );
      

  3.   

    使用Unicode字符集就不要用char数组来储存字符串了,改用TCHAR/WCHAR数组。如果需要多字节与Unicode字符集相互转换,可以用MultiByteToWideChar和WideCharToMultiByte。
      

  4.   

    char数组存的是什么编码呢? Ansi? UTF7。UTF8?没有这个前提,代码都是不对的。
    如果你知道这些信息了。只要  CString a = CA2W("Hello您好", CP_ACP); CString a2 = CA2W("Hello World", CP_UTF8);两个例子,你的工程include atlconv.h即可。
      

  5.   

    char* -> CString
    char buf[] = "...";
    CString str(buf);CString -> char*
    #include <atlbase.h>
    USES_CONVERSION;
    T2A();
      

  6.   

    CString 是 被定义成 CSTringA 和 CStringW的可以用ATL 宏,也可以直接调用API来转
      

  7.   

    什么宏都不需要调用了,看你用的VS是哪个版本,至少我在VS2008上可以直接赋值:
    CString str = L"hello";
    CString str2 = "hello";
    无论项目是ANSI还是UNICODE都能编译通过。ATL和MFC共用的 CString(A/W)内部自动转换编码。
      

  8.   

    char aaa[100];
    Cstring str;
    char *ptmp; ptmp = str.GetBuffer(str.SetLenghth(100));
     memcpy(ptmp,aaa,100); 完!
      

  9.   

    使用函数_tcscpy_s:CString theString( "This is a test" );
    int    sizeOfString = (theString.GetLength() + 1);
    LPTSTR  lpsz = new TCHAR[ sizeOfString ];
    _tcscpy_s(lpsz, sizeOfString, theString);最后再转换一下lpsz为const型的LPTSTR在UNICODE环境下编译是wchar_t类型
      

  10.   


    引入#include <atlbase.h>
    得加上宏命令启动
    USES_CONVERSION;
      

  11.   

    还可以用Format, %S/%s等来转换
      

  12.   

    楼上各位说的很全了
    如果是char数组没有 '\0'结束符,就用WideCharToMultiByte/MultiByteToWideChar这个方式好了