各种数据类型,转来转去的,好晕,整理一下,看会不会不晕一点。
1、MFC CString与int、float、double、char*、string等类型的转化
//宽字符的话 L -- _T 成对使用 //CString 的头文件:<afx.h> //CString <--> int CString str = "100"; int i = _ttoi(str); str.Format("%d",i); //CString <-->float CString str = "100"; float f = _ttof(str); str.Format("%.3f", f); //CString<-->double CString str = "100"; double d = _ttol(str); str.Format("%.3l", d ); //CString<-->char * CString str = "100"; char *pBuf = str.GetBuffer( 0 ); //使用完后及时释放,才使用使用其它的CString成员函数 str.Format("%s", pBuf ); str.ReleaseBuffer(); //CString<-->string //string 的头文件:<iostream>,<string>,using namespace std; CString cstr = "100"; string str = cstr.GetBuffer( 0 ); str = LPCSTR(cstr); cstr.format( "%s", str.c_str()); cstr.format( "%s", str.data()); cstr.ReleaseBuffer();
2、UNICODE编译模式下,char和wchar_t时常需要进行转化,参考http://www.cnblogs.com/gdutbean/archive/2012/03/31/2427609.html
char* w2c(const wchar_t* wp) { char *m_char; int len = WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), NULL, 0, NULL, NULL); m_char = new char[len + 1]; WideCharToMultiByte(CP_ACP, 0, wp, wcslen(wp), m_char, len, NULL, NULL); m_char[len] = '\0'; return m_char; } void c2w(wchar_t *pwstr, size_t len, const char *str) { if (str) { size_t nu = strlen(str); size_t n = (size_t)MultiByteToWideChar(CP_ACP, 0, (const char *)str, (int)nu, NULL, 0); if (n >= len)n = len - 1; MultiByteToWideChar(CP_ACP, 0, (const char *)str, (int)nu, pwstr, (int)n); pwstr[n] = 0; } }
下面是其他常用函数的处理,参考来源http://blog.csdn.net/mrandexe/article/details/6252080
/*---------------------------------------- File: m_fun.h 使用宏定义同函数名可以避免修改编译器编译环境 -----------------------------------------*/ #pragma once #ifndef M_FUN_H #define M_FUN_H #ifdef UNICODE #define _mstrncpy wcsncpy #define _mstrcpy wcscpy #define _mstrlen wcslen #define _mstrcat wcscat #define _mstrcmp wcscmp #else #define _mstrncpy strncpy #define _mstrcpy strcpy #define _mstrlen strlen #define _mstrcat strcat #define _mstrcmp strcmp #endif #endif
3、结束