面对现实,超越自己
逆水行舟,不进则退
posts - 269,comments - 32,trackbacks - 0
MFC 类型转换

一、CString与LPSTR、LPCSTR、string、 char*相互转换

1. CString转换成LPSTR:
方法一:   
1  CString strFileName;    
2  LPSTR lpStr = strFileName.GetBuffer();  
3  strFileName.ReleaseBuffer();  
方法二:     
1 CString strFileName;   
2  LPSTR lpStr = (LPSTR)(LPCSTR)strFimeName;
3 

2. LPSTR转换成CString:

1 LPSTR lpStr = _T("TestStr");   
2 CString str(lpStr);   
3 //注意:CString和LPCSTR可直接转换,如下:   
4 CString str;   
5 LPCSTR lpcStr = (LPCSTR)str;

CString转换成LPSTR:
CString strTemp;
LPTSTR pSterTemp = strTemp.GetBuffer();  //这会为pSetTemp指向的字符串分配内存,同时会把strTemp的内容拷贝下来。。
strTemp.ReleaseBuffer();  //must call this funtion. 归还内存给操作系统。

或:
LPTSTR pSterTemp = (LPTSTR)(LPCSTR)strTemp;

3.string 转 CString  
1 CString.format("%s"string.c_str());

4.CString 转 string 

1 string s(CString.GetBuffer(CString.GetLength()));

5. CString转char*

(1)传给未分配内存的const char* (LPCTSTR)指针.      

1 CString cstr(asdd);
2 const char* ch = (LPCTSTR)cstr;
3 //ch指向的地址和cstr相同。但由于使用const保证ch不会修改,所以安全.

 

(2)传给未分配内存的指针.   

CString cstr = "ASDDSD";
char *ch = cstr.GetBuffer(cstr1.GetLength() + 1);
cstr.ReleaseBuffer();
//修改ch指向的值等于修改cstr里面的值.
//PS:用完ch后,不用delete ch,因为这样会破坏cstr内部空间,容易造成程序崩溃.

(3)第二种用法。把CString 值赋给已分配内存的char *.

1 CString cstr1 = "ASDDSD";
2 int strLength = cstr1.GetLength() + 1;
3 char *pValue = new char[strLength];
4 strncpy(pValue, cstr1, strLength);

(4)第三种用法.把CString 值赋给已分配内存char[]数组.

1 CString cstr2 = "ASDDSD";
2 int strLength1 = cstr1.GetLength() + 1;
3 char chArray[100];
4 memset(chArray,0sizeof(bool* 100); //将数组的垃圾内容清空.

 6、char * 转 CString  

1 CString.format("%s"char*);

      
二、string与char*转换

1、char * 转 string 

1 string s(char *);

 2、string 转 char *        

1 char *= string.c_str();


三、CString转换到TCHAR *
1、使用强制转换。例如:

1 CString theString( "This is a test" );
2 LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString;

2、使用strcpy。例如:

1 CString theString( "This is a test" );
2 LPTSTR lpsz = new TCHAR[theString.GetLength()+1];
3 _tcscpy(lpsz, theString); 
4 
5 //需要说明的是,strcpy(或可移值Unicode/MBCS的_tcscpy)的第二个参数是 const wchar_t* (Unicode)或const char* (ANSI),系统编译器将会自动对其进行转换。

3、使用CString::GetBuffer。例如:

1 CString s(_T("This is a test "));
2 LPTSTR p = s.GetBuffer();
3 // 在这里添加使用p的代码
4 if(p != NULL) *= _T('\0');
5     s.ReleaseBuffer(); 
6 // 使用完后及时释放,以便能使用其它的CString成员函数


四、stringwstring

1     wchar_t wcs[100], wc;
2 
3     string testStr1="1234567890";
4 
5     setlocale(LC_CTYPE, "");  //很重要,没有这一句,转换会失败
6 
7     mbstowcs(wcs, testStr1.c_str(), 99);
8 
9     wstring testStr(wcs);
  
#include <string>
std::string ws2s(const std::wstring& ws)
{
    std::string curLocale = setlocale(LC_ALL, NULL);        // curLocale = "C";
    setlocale(LC_ALL, "chs");
    const wchar_t* _Source = ws.c_str();
    size_t _Dsize = 2 * ws.size() + 1;
    char *_Dest = new char[_Dsize];
    memset(_Dest,0,_Dsize);
    wcstombs(_Dest,_Source,_Dsize);
    std::string result = _Dest;
    delete []_Dest;
    _Dest = NULL;
    setlocale(LC_ALL, curLocale.c_str());
    return result;
}

std::wstring s2ws(const std::string& s)
{
    setlocale(LC_ALL, "chs"); 
    const char* _Source = s.c_str();
    size_t _Dsize = s.size() + 1;
    wchar_t *_Dest = new wchar_t[_Dsize];
    wmemset(_Dest, 0, _Dsize);
    mbstowcs(_Dest,_Source,_Dsize);
    std::wstring result = _Dest;
    delete []_Dest;
    _Dest = NULL;
    setlocale(LC_ALL, "C");
    return result;
}

C语言库函数名: atoi   功 能: 把字符串转换成整型数
函数名: atof   功 能: 把字符串转换成浮点数

CString与Byte数组相互转换

 CString cs1 = "gettruckpos";

 byte buf[200];

 memcpy(buf,cs1.GetBuffer(cs1.GetLength()),cs1.GetLength());  //将cstring放入byte数组

 CString *pPhoneNum =new CString((char*)buf, cs1.GetLength()); //将byte数组转换成cstring

 CString cs2 = *pPhoneNum;

int转byte
//int转byte
void  intToByte(int i,byte *bytes,int size = 4)
{
    byte[] bytes = new byte[4];
    memset(bytes,0,sizeof(byte) *  size);
    bytes[0] = (byte) (0xff & i);
    bytes[1] = (byte) ((0xff00 & i) >> 8);
    bytes[2] = (byte) ((0xff0000 & i) >> 16);
    bytes[3] = (byte) ((0xff000000 & i) >> 24);
    return ;
 }

BYTE*  IntToBytes(int nNum, BOOL isHighFirst, BYTE *pVal)
{
    BYTE result[4] = {0};

    if (isHighFirst)
    {
        result[0]  = (BYTE)(nNum >> 24 & 0xff);
        result[1]  = (BYTE)(nNum >> 16 & 0xff);
        result[2]  = (BYTE)(nNum >> 8 & 0xff);
        result[3]  = (BYTE)(nNum & 0xff);
    }
    else
    {
        result[3]  = (BYTE)(nNum >> 24 & 0xff);
        result[2]  = (BYTE)(nNum >> 16 & 0xff);
        result[1]  = (BYTE)(nNum >> 8 & 0xff);
        result[0]  = (BYTE)(nNum & 0xff);
    }

    memcpy(pVal, result, 4);

    return result;
}

byte转int
//byte转int
int bytesToInt(byte* bytes,int size = 4) 
{
    int addr = bytes[0] & 0xFF;
    addr |= ((bytes[1] << 8) & 0xFF00);
    addr |= ((bytes[2] << 16) & 0xFF0000);
    addr |= ((bytes[3] << 24) & 0xFF000000);
    return addr;
 }

CString转 wchar_t*
wchar_t * CCommonFun::ConvertCStringToWchar_t(CString &str)
{
    CString sTemp = str;
    const char* CStr = (LPCTSTR)sTemp;

    size_t len = strlen(CStr) + 1;
    size_t converted = 0;
    wchar_t *WStr;
    WStr = (wchar_t*)malloc(len*sizeof(wchar_t));
    mbstowcs_s(&converted, WStr, len, CStr, _TRUNCATE);

    return WStr;
}
 注意:可以在调用的地方释放分配的内存,如果遇到汉子转换乱码问题可以在转换前使用setlocale(LC_ALL, "chs")或者setlocale(LC_ALL,"zh_CN.UTF-8")进行设置

wchar_t*转CString
CString  CTestTextToPicDlg::ConvertWchar_tToCString(const wchar_t* WStr)
{
    size_t len = wcslen(WStr) + 1;
    size_t converted = 0;
    char *CStr;
    CStr=(char*)malloc(len*sizeof(char));
    wcstombs_s(&converted, CStr, len, WStr, _TRUNCATE);
    CString sTemp;
    sTemp.Format("%s", CStr);

    free(CStr);
    CStr = NULL;

    return sTemp;
}

TCHAR和char的区别:

C++支持两种字符串,即常规的ANSI编码(使用""包裹)和Unicode编码(使用L""包裹),这样对应的就有了两套字符串字符串处理函数,比如:strlen和wstrlen,分别用于处理两种字符串。

 

由于字符编码的不同,在C++中有三种对于字符类型:char, wchar_t , TCHAR。其实TCHAR不能算作一种类型,他紧紧是一个宏。我们都知道,宏在预编译的时候会被替换成相应的内容。TCHAR 在使用多字节编码时被定义成char,在Unicode编码时定义成wchar_t。
如果你希望同时为ANSI和Unicode编译的源代码,那就要include TChar.h。TCHAR是定义在其中的一个宏,它视你是否定义了_UNICODE宏而定义成char或者wchar_t。如果你使用了TCHAR,那么就不应该使用ANSI的strXXX函数或者Unicode的wcsXXX函数了,而必须使用TChar.h中定义的_tcsXXX函数。另外,为了解决刚才提到带“L”的问题,TChar.h中定义了一个宏:“_TEXT”。

 以strcpy函数为例子,总结一下:
 .如果你想使用ANSI字符串,那么请使用这一套写法:
 char szString[100];
 strcpy(szString,"test");
 .如果你想使用Unicode字符串,那么请使用这一套:
 wchar_t szString[100];
 wcscpyszString,L"test");
 .如果你想通过定义_UNICODE宏,而编译ANSI或者Unicode字符串代码:
 TCHAR szString[100];
 _tcscpy(szString,_TEXT("test"));

使用TCHAR系列方案编写程序
    TCHAR是一种字符串类型,它让你在以MBCS和UNNICODE来build程序时可以使用同样的代码,不需要使用繁琐的宏定义来包含你的代码。 
      TCHAR的引入,主要是在Tchar.h文件中,该文件包含这方面的重要的定义信息。
      对于包含了对str函数或wcs函数进行显式调用的代码来说,无法非常容易地同时为ANSI和Unicode对这些代码进行编译。本章前面说过,可以创建同时为ANSI和Unicode进行编译的单个源代码文件。若要建立双重功能,必须包含TChar.h文件,而不是包含String.h文件。
      TChar.h文件的唯一作用是帮助创建ANSI/Unicode通用源代码文件。它包含你应该用在源代码中的一组宏,而不应该直接调用str函数或者 wcs函数。如果在编译源代码文件时定义了_UNICODE,这些宏就会引用wcs这组函数。如果没有定义_UNICODE,那么这些宏将引用str这组宏。
      TCHAR的定义如下:
      #ifdef UNICODE
      typedef wchar_t TCHAR;
      #else
      typedef char TCHAR;
      #endif
      所以用MBCS来build时,TCHAR是char,使用UNICODE时,TCHAR是wchar_t。
      还有一个宏来处理定义Unicode字符串常量时所需的L前缀。
      #ifdef UNICODE
      #define _T(x) L##x
      #define _TEXT(x) L##x
      #define __T(x) L##x
      #else
      #define _T(x) x
      #define _TEXT(x) x
      #define __T(x) x
      #endif
     ## 是一个预处理操作符,它可以把两个参数连在一起。如果你的代码中需要字符串常量,在它前面加上_T宏。如果你使用Unicode来build,它会在字符串常量前加上L前缀。
      TCHAR szNewText[] = _T("we love Bob!");
    _UNICODE宏用于C运行期头文件,而UNICODE宏则用于Windows头文件。当编译源代码模块时,通常必须同时定义这两个宏。
  像是用宏来隐藏SetWindowTextA/W的细节一样,还有很多可以供你使用的宏来实现str***()和_mbs***()等字符串函数。例如,你可以使用_tcsrchr宏来替换strrchr()、_mbsrchr()和wcsrchr()。_tcsrchr根据你预定义的宏是_MBCS还是 UNICODE来扩展成正确的函数,就象SetWindowText所作的一样。
   不仅str***()函数有TCHAR宏。其他的函数如, _stprintf(代替sprinft()和swprintf()),_tfopen(代替fopen()和_wfopen())。 MSDN中"Generic-Text Routine Mappings."标题下有完整的宏列表。

QT类型转换

QString转char*

Qstring  str;

char*  ch;

QByteArray ba = str.toLatin1();    

ch=ba.data();

 

这样就完成了QString向char*的转化。经测试程序运行时不会出现bug

注意第三行,一定要加上,不可以str.toLatin1().data()这样一部完成,可能会出错。

补充:以上方法当QString里不含中文时,没有问题,但是QString内含有中文时,转换为char*就是乱码,采用如下方法解决:

方法1:

添加GBK编码支持:

#include <QTextCodec>

QTextCodec::setCodecForTr(QTextCodec::codecForName("GBK"));
QTextCodec::setCodecForLocale(QTextCodec::codecForName("GBK"));

然后改变上面的第三行为:QByteArray ba = str.toLoacl8Bit();      toLoacl8Bit支持中文

方法2:

先将QString转为标准库中的string类型,然后将string转为char*,如下:

std::string str = filename.toStdString();

const char* ch = str.c_str();

 

posted on 2012-04-06 17:08 王海光 阅读(967) 评论(0)  编辑 收藏 引用 所属分类: C++

只有注册用户登录后才能发表评论。
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理