程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> C語言 >> C++ >> C++入門知識 >> 實戰c++中的string系列--std::string與MFC中CString的轉換

實戰c++中的string系列--std::string與MFC中CString的轉換

編輯:C++入門知識

實戰c++中的string系列--std::string與MFC中CString的轉換


搞過MFC的人都知道cstring,給我們提供了很多便利的方法。

CString 是一種很有用的數據類型。它們很大程度上簡化了MFC中的許多操作,使得MFC在做字符串操作的時候方便了很多。不管怎樣,使用CString有很多特殊的技巧,特別是對於純C背景下走出來的程序員來說有點難以學習。

但是很多情況下,我們還是需要cstring和string的轉換。
分兩步:
1把cstring轉為char數組
2根據char數組,構造自己的string(記得釋放內存)

std::string CStringToSTDStr(const CString& theCStr)
{
    const int theCStrLen = theCStr.GetLength();
    char *buffer = (char*)malloc(sizeof(char)*(theCStrLen+1));
    memset((void*)buffer, 0, sizeof(buffer));
    WideCharToMultiByte(CP_UTF8, 0, static_cast(theCStr).GetBuffer(), theCStrLen, buffer, sizeof(char)*(theCStrLen+1), NULL, NULL);

    std::string STDStr(buffer);
    free((void*)buffer);
    return STDStr;
}

而string轉cstring那就很輕松了:

string str="abcde";
CString cstr(str.c_str());

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved