CString
非常方便,而std::string
与STL容器更兼容。我正在使用hash_map
。但是,hash_map
不支持CString
s作为键,所以我想将CString
转换为std::string
。
编写一个CString
散列函数似乎需要花费很多时间。
CString -----> std::string
我该怎么做呢?
std::string -----> CString:
inline CString toCString(std::string const& str)
{
return CString(str.c_str());
}
我说的对吗?
编辑:
以下是更多问题:
如何在wstring
和CString
之间相互转换?
// wstring -> CString
std::wstring src;
CString result(src.c_str());
// CString -> wstring
CString src;
std::wstring des(src.GetString());
这有什么问题吗?
另外,如何在std::wstring
和std::string
之间相互转换?
发布于 2008-11-03 09:36:37
通过使用std::basic_string<TCHAR>
而不是std::string
来解决这个问题,不管您的角色设置如何,它都应该工作得很好。
发布于 2011-06-03 21:49:15
使用指定长度的转换将CString
转换为std::string
更有效。
CString someStr("Hello how are you");
std::string std(someStr, someStr.GetLength());
在紧凑的循环中,这会显著提高性能。
发布于 2009-07-12 15:05:25
如果你想要更像C++的东西,这就是我所用的。虽然它依赖于Boost,但这只是针对例外情况。您可以很容易地删除那些使其仅依赖于STL和WideCharToMultiByte()
Win32应用编程接口调用的代码。
#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);
}
https://stackoverflow.com/questions/258050
复制相似问题