VC++中char和TCHAR之間轉換


char:計算機編程語言(c、c++、java等)中可容納單個字符的一種基本數據類型。

TCHAR:為了滿足Unicode編碼,對char的擴展,即_T(“str”)表示TCHAR類型

C++支持兩種字符串,即常規的ANSI編碼(使用""包裹)和Unicode編碼(使用L""包裹),這樣對應的就有了兩套字符串字符串處理函數,比如:strlen和wcslen,分別用於處理兩種字符串char和TCHAR類型

 

winnt.h頭文件中:

     typedef WCHAR TCHAR, *PTCHAR; 

表明 TCHAR 與 WCHAR 屬同一類型

 

char szA[100];                    // ANSI string buffer
WCHAR szW[100];            // Unicode string buffer

// Normal sprintf: all strings are ANSI
sprintf(szA, "%s","ANSI Str");

// Converts Unicode string to ANSI
sprintf(szA,"%S",L"Unicode Str");

// Normal swprintf: all strings are Unicode
swprintf(szW,L"%s",L"Unicode Str");

// Converts ANSI string to Unicode
swprintf(szW,L"%S", "ANSI Str");

注意:大寫S 和小寫s 的使用

 ===========================

 

 應用實例:通過system函數程序調用啟動msc程序

 

void WSUS::OnBnClickedOk()  
{  
    CString strPath = NULL;    // 申請路徑字符串(TCHAR)  
    char strChar[256];           // 申請路徑字符串(char)  
  
    m_CustomEdit.GetWindowTextW(strPath);   // 獲取路徑存儲到strPath  
  
    strPath.Replace(_T("\\"), _T("\\\\"));  // 替換strPath中"\"為"\\",注意轉換符  
    //sprintf(strChar, "%s %S", "mmc.exe", strPath);        // TCHAR轉換char類型  
    sprintf(strChar, "mmc.exe \"%S\"", strPath);        // TCHAR轉換char類型  
  
    MessageBox(strPath, _T("title"));  
    system(strChar);                        // 系統函數調用啟動msc程序  
              
    //WinExec((LPCSTR)_bstr_t(strPath), SW_SHOW);   // 調用exe程序  
}  

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM