【问题标题】:Conversion from string to wstring is causing ú to lose encoding从字符串到 wstring 的转换导致 ú 丢失编码
【发布时间】:2011-01-24 21:59:21
【问题描述】:

变量filepath 是一个string 包含值Música。我有以下代码:

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

fp 然后包含值M?sica。如何在不丢失 ú 字符编码的情况下将 filepath 转换为 fp

【问题讨论】:

    标签: string mfc encoding wstring


    【解决方案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;
    }
    

    【讨论】:

      【解决方案2】:

      由于您使用的是 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));
      

      【讨论】:

        猜你喜欢
        • 2016-03-27
        • 2011-05-20
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-06-09
        • 1970-01-01
        相关资源
        最近更新 更多