2

である変数filepathにはstring値が含まれますMúsica。次のコードがあります。

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

fp値が含まれますM?sica。ú 文字のエンコーディングを失わずに に変換filepathするにはどうすればよいですか?fp

4

2 に答える 2

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;
}
于 2010-03-08T10:22:14.497 に答える
0

MFC を使用しているため、 ATL String Conversion Macrosにアクセスできます。

これにより、 を使用する場合と比較して、変換が大幅に簡素化されMultiByteToWideCharます。システムのデフォルトのコードページでエンコードされていると仮定するとfilepath、これでうまくいくはずです:

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

がシステムのデフォルト コード ページ (UTF-8 としましょう) にない場合filepathは、変換元のエンコーディングを指定できます。

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));
于 2010-03-09T20:53:37.480 に答える