首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >如何将CString和std::string std::wstring相互转换?

如何将CString和std::string std::wstring相互转换?
EN

Stack Overflow用户
提问于 2008-11-03 06:58:46
回答 16查看 225K关注 0票数 81

CString非常方便,而std::string与STL容器更兼容。我正在使用hash_map。但是,hash_map不支持CStrings作为键,所以我想将CString转换为std::string

编写一个CString散列函数似乎需要花费很多时间。

代码语言:javascript
运行
复制
CString -----> std::string

我该怎么做呢?

代码语言:javascript
运行
复制
std::string -----> CString:

inline CString toCString(std::string const& str)
{
    return CString(str.c_str()); 
}

我说的对吗?

编辑:

以下是更多问题:

如何在wstringCString之间相互转换?

代码语言:javascript
运行
复制
// wstring -> CString
std::wstring src;
CString result(src.c_str());

// CString -> wstring
CString src;
std::wstring des(src.GetString());

这有什么问题吗?

另外,如何在std::wstringstd::string之间相互转换?

EN

回答 16

Stack Overflow用户

发布于 2008-11-03 09:36:37

通过使用std::basic_string<TCHAR>而不是std::string来解决这个问题,不管您的角色设置如何,它都应该工作得很好。

票数 36
EN

Stack Overflow用户

发布于 2011-06-03 21:49:15

使用指定长度的转换将CString转换为std::string更有效。

代码语言:javascript
运行
复制
CString someStr("Hello how are you");
std::string std(someStr, someStr.GetLength());

在紧凑的循环中,这会显著提高性能。

票数 7
EN

Stack Overflow用户

发布于 2009-07-12 15:05:25

如果你想要更像C++的东西,这就是我所用的。虽然它依赖于Boost,但这只是针对例外情况。您可以很容易地删除那些使其仅依赖于STL和WideCharToMultiByte() Win32应用编程接口调用的代码。

代码语言:javascript
运行
复制
#include <string>
#include <vector>
#include <cassert>
#include <exception>

#include <boost/system/system_error.hpp>
#include <boost/integer_traits.hpp>

/**
 * Convert a Windows wide string to a UTF-8 (multi-byte) string.
 */
std::string WideStringToUtf8String(const std::wstring& wide)
{
    if (wide.size() > boost::integer_traits<int>::const_max)
        throw std::length_error(
            "Wide string cannot be more than INT_MAX characters long.");
    if (wide.size() == 0)
        return "";

    // Calculate necessary buffer size
    int len = ::WideCharToMultiByte(
        CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()), 
        NULL, 0, NULL, NULL);

    // Perform actual conversion
    if (len > 0)
    {
        std::vector<char> buffer(len);
        len = ::WideCharToMultiByte(
            CP_UTF8, 0, wide.c_str(), static_cast<int>(wide.size()),
            &buffer[0], static_cast<int>(buffer.size()), NULL, NULL);
        if (len > 0)
        {
            assert(len == static_cast<int>(buffer.size()));
            return std::string(&buffer[0], buffer.size());
        }
    }

    throw boost::system::system_error(
        ::GetLastError(), boost::system::system_category);
}
票数 5
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/258050

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档