CSting 类型转换

格式:

CString cstr.AppendFormat(_T(" %.4f "), );

输出:

(1)

https://blog.csdn.net/overlord_bingo/article/details/60140224

不含中文的情况下:

CString s("hello world");

wcout << "s=" << s.GetString() << endl;

wcout << "s=" << (LPCTSTR)s << endl;\类型转换
wcout << "s=" << s.GetBuffer()<< endl;

含有中文的情况下需要添加:

wcout.imbue(std::locale("chs"));

如下

CString s("hello world");

wcout.imbue(std::locale("chs"));

wcout << "s=" << s.GetString() << endl;

wcout << "s=" << (LPCTSTR)s << endl;
wcout << "s=" << s.GetBuffer()<< endl;

(2)CString是unicode编码

CString a = "test";
printf("%S ", a);//输出test;

printf("%s ", a);//输出t;

指针:

类型转换:

(1)LPCTSTR是把CString类型的强制转换为常字符串 LPCTSTR相当于const char*;输出 :例如 CString str; 要用printf输出str printf("%s",(LPCTSTR)str);

2)CString 值赋给已分配内存的char*

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

(3)char[]、char*、string转换成CString

  1.     char *ch = "Hello";  
  2.     string s = "Wrold";  
  3.     char  chr[]="name";
  4.     CString cstr1(ch), cstr2(s.c_str()), cstr3("Program"), cstr4(chr);
  5. cstr2.Format("%s", s.c_str());
  6. cstr2.Format("%s", s.data());

c_str()和data()区别是:前者返回带'/0'的字符串,后者则返回不带'/0'的字符串.

(5)CString转换成char*

  若将CString类转换成char*(LPSTR)类型,常常使用下列三种方法:
  方法一,使用强制转换。例如:
  CString theString( "This is a test" );
  LPTSTR lpsz =(LPTSTR)(LPCTSTR)theString; 

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

  方法三,使用CString::GetBuffer。例如:
  CString s(_T("This is a test "));
  LPTSTR p = s.GetBuffer();
  // 在这里添加使用p的代码
  if(p != NULL) *p = _T('');
  s.ReleaseBuffer();
  // 使用完后及时释放,以便能使用其它的CString成员函数

(6)CString -> string 

      string  s(CString.GetBuffer());  
      GetBuffer()后一定要ReleaseBuffer(),否则就没有释放缓冲区所占的空间.

 (7) CString->char[]

strcpy_s(char[255], CString.GetBuffer());

sprintf_s(char[255], CString.GetBuffer());

附注:

原文地址:https://www.cnblogs.com/wllwqdeai/p/10002867.html