Error 1 error C2440: 'initializing' : cannot convert from 'wchar_t *' to 'char *'

VS2008下面將 CString轉化爲char* 的問題


 使用CString的GetBuffer方法
        CString origCString("Hello,World");
        char* CharString = origCString.GetBuffer(origCString.GetLength()+1);
    網上的很多文章說的都是這個方法,但是我在VC++2008中編譯得到下列信息
        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++2008中的各種字符串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++2008下面去不能直接使用,還要通過轉換呢?正好看到《Programming Windows》的第二章講Unicode的和在msdn論壇問了一下相關問題後得到答案。

解決方法:
   原來在VC++ 2005以前,應用程序默認都是關閉對Unicode的支持的,而在VC2005後,默認打開了對它的支持,CString對應的字符串應該是TCHAR,TCHAR的定義是這樣的,
        #ifdef _UNICODE
        typedef wchar_t TCHAR    ;
        #else
        typedef char TCHAR;
        #endif
我想這個就是爲什麼我在VC++2008種不能直接轉換的原因。在工程中應該可以關閉對於Unicode的支持,從而可以直接轉換。這個做法是右擊工程名 —〉Property—〉General中的character set中選擇not set,這樣,本文開頭的那段代碼就可以正確的執行了。


注:轉自 http://blog.sina.com.cn/s/blog_7e5eb91b0100ys13.html
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章