CString 转换为 char* (VC6.0与Visual Studio 2005兼容问题)UNICODE字符集

来源:互联网 发布:nginx laravel 路由 编辑:程序博客网 时间:2024/06/05 18:25

 

http://hi.baidu.com/proworkspace/blog/item/50cdee44b03f1d86b2b7dc44.html

 

使用CString的GetBuffer方法
        CString origCString("Hello,World");
        char* CharString = origCString.GetBuffer(origCString.GetLength()+1);

    网上的很多文章说的都是这个方法,但是我在VC++2005中编译得到下列信息
        Error 1 error C2440:   'initializing' : cannot convert from 'wchar_t *' to 'char *'  
    对于这个错误不是很理解,因为是刚开始使用VC不久,所以对于wchar_t和char的区别不是很清楚,在MSDN中查看了一下,wchar_t是一个宽字符型,相当于unsigned short(16bit)。而我们通常使用的char是8bit。继续搜索wchar_t*到char*的转换,msdn上面有一篇文章是Convert Between Various String Types,讲了VC++2005中的各种字符串char *, wchar_t*, _bstr_t, CComBSTR, CString, basic_string, and System.String的相互转换。其中将wchar_t*转换为char*的代码如下:(为了保持文章的一致性,修改了变量名)
        #include <stdlib.h>
        #include <iostream>
        using namespace std;
        int main()
        {
          wchar_t *origString = L"Hello,World";
          wcout << origString << endl;

          // Convert to a char*
          size_t origsize = wcslen(origString) + 1;
          const size_t newsize = 100;
          size_t convertedChars = 0;
          char CharString[newsize];
          wcstombs_s(&convertedChars, CharString, origsize, origString , _TRUNCATE);
          cout << CharString << endl;
        }   

   输出正确,均为Hello, World!
   结合上面的两段,看看能不能将CString转换为char*
        CString origCString("Hello, World!");
        wchar_t* wCharString = origCString.GetBuffer(origCString.GetLength()+1);
        size_t origsize = wcslen(wCharString) + 1;
        size_t convertedChars = 0;
        char *CharString;
        CharString=new char(origsize);
        wcstombs_s(&convertedChars, CharString, origsize, wCharString , _TRUNCATE);
        cout << CharString << endl;

   成功输出字符串"Hello,World"
   至于为什么原来的那段代码别人都能用好,而我在VC++2005下面去不能直接使用,还要通过转换呢?正好看到《Programming Windows》的第二章讲Unicode的和在msdn论坛问了一下相关问题后得到答案。
   原来在VC++ 2005以前,应用程序默认都是关闭对Unicode的支持的,而在VC2005中,默认打开了对它的支持,CString对应的字符串应该是TCHAR,TCHAR的定义是这样的,
        #ifdef _UNICODE
        typedef wchar_t TCHAR    ;
        #else
        typedef char TCHAR;
        #endif

我想这个就是为什么我在VC++2005种不能直接转换的原因。在工程中应该可以关闭对于Unicode的支持,从而可以直接转换。这个做法是右击工程名—〉Property—〉General中的character set中选择not set,这样,本文开头的那段代码就可以正确的执行了。
原创粉丝点击