C++ 常見的類型轉換

1、CString——>string

/*注意,一定要加USES_CONVERSION   包含頭文件#include "afxpriv.h" */
1、USES_CONVERSION; 
    CString a = FilePathName; 
    string  b; 
    char* p = T2A(a); 
    b = p;
2、CString CstrInputFile = FilePathName;
    std::string StrIputFile( CW2A( CstrInputFile.GetString()));

2、CString——>const char*

   CString a = FilePathName; 
    const char* p = T2A(a); 

3、輸出int、float類型

   CString str;
   Str.Format(_T(“%d”),width);  
   Str.Format(_T(“%f”),width);

4、CString->float

   CString b;
   float a=(float)wcstod(b,NULL);
   CString->int
   CString b;
   int a=_wtoi(b);
   const char*->int
   const char* b;
   int a=_atoi(b);

5、 TCHAR->float

TCHAR scale[10]={0};
float n = _ttof(scale);

6、TCHAR->string

std::string TCHAR2STRING(TCHAR *tstr)
{
      int iLen = WideCharToMultiByte(CP_ACP, 0,tstr, -1, NULL, 0, NULL, NULL);
      char* chRtn =new char[iLen*sizeof(char)];
      WideCharToMultiByte(CP_ACP, 0, tstr, -1, chRtn, iLen, NULL, NULL);
      std::string str(chRtn);
      return str;
}

7、TCHAR->char

char* tchartochar(TCHAR *tchar)
{
      LPSTR pszOut = NULL;

      if(tchar != NULL){
            int nInputStrLen = wcslen(tchar);

            int nOutputStrLen = WideCharToMultiByte(CP_ACP, 0, tchar, nInputStrLen, NULL, 0, 0, 0) + 2;

            pszOut = new char[nOutputStrLen];

            if(pszOut){
                  memset(pszOut, 0x00, nOutputStrLen);
                 WideCharToMultiByte(CP_ACP, 0, tchar, nInputStrLen, pszOut, nOutputStrLen, 0, 0);
            }
      }
      return pszOut;
}

8.stringtotchar

TCHAR* stringtotchar(string s)   //Change string to TCHAR
{
    //TCHAR *tchar=_T("");
    static TCHAR tchar[256]=_T("");
    _tcscpy_s(tchar, 256 , CA2T(s.c_str()));        // s.length()
    return tchar;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章