可变filepath
其是string
包含值Música
。我有以下代码:转换导致ú失去编码
wstring fp(filepath.length(), L' ');
copy(filepath.begin(), filepath.end(), fp.begin());
fp
则包含值M?sica
。如何转换filepath
到fp
不失编码的字符ú?
可变filepath
其是string
包含值Música
。我有以下代码:转换导致ú失去编码
wstring fp(filepath.length(), L' ');
copy(filepath.begin(), filepath.end(), fp.begin());
fp
则包含值M?sica
。如何转换filepath
到fp
不失编码的字符ú?
使用功能的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;
}
由于您使用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::wstring
到std::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));