2010-03-08 30 views
2

可變filepath其是string包含值Música。我有以下代碼:轉換導致ú失去編碼

wstring fp(filepath.length(), L' '); 
copy(filepath.begin(), filepath.end(), fp.begin()); 

fp則包含值M?sica。如何轉換filepathfp不失編碼的字符ú?

回答

1

使用功能的MultiByteToWideChar。

示例代碼:

std::string toStdString(const std::wstring& s, UINT32 codePage) 
{ 
    unsigned int bufferSize = (unsigned int)s.length()+1; 
    char* pBuffer = new char[bufferSize]; 
    memset(pBuffer, 0, bufferSize); 
    WideCharToMultiByte(codePage, 0, s.c_str(), (int)s.length(), pBuffer, bufferSize, NULL, NULL); 
    std::string retVal = pBuffer; 
    delete[] pBuffer; 
    return retVal; 
} 

std::wstring toStdWString(const std::string& s, UINT32 codePage) 
{ 
    unsigned int bufferSize = (unsigned int)s.length()+1; 
    WCHAR* pBuffer = new WCHAR[bufferSize]; 
    memset(pBuffer, 0, bufferSize*sizeof(WCHAR)); 
    MultiByteToWideChar(codePage, 0, s.c_str(), (int)s.length(), pBuffer, bufferSize); 
    std::wstring retVal = pBuffer; 
    delete[] pBuffer; 
    return retVal; 
} 
0

由於您使用MFC,你可以訪問ATL String Conversion Macros

這大大簡化了轉換與利用MultiByteToWideChar。假設filepath在您的系統的默認代碼頁編碼,這應該做的伎倆:

CA2W wideFilepath(filepath.c_str()); 
wstring fp(static_cast<const wchar_t*>(wideFilepath)); 

如果filepath在系統的默認代碼頁(假設它是在UTF-8),那麼你就可以指定編碼轉換來自:

CA2W wideFilepath(filepath.c_str(), CP_UTF8); 
wstring fp(static_cast<const wchar_t*>(wideFilepath)); 

要的其他方式轉換,從std::wstringstd::string,你可以這樣做:

// Convert from wide (UTF-16) to UTF-8 
CW2A utf8Filepath(fp.c_str(), CP_UTF8); 
string utf8Fp(static_cast<const char*>(utf8Filepath)); 

// Or, convert from wide (UTF-16) to your system's default code page. 
CW2A narrowFilepath(fp.c_str(), CP_UTF8); 
string narrowFp(static_cast<const char*>(narrowFilepath));