c++ - 转换 xchar* std::string

标签 c++ visual-studio-2010

我最近遇到了一段类型为 XCHAR* 的 C++ 代码。我想知道这种类型是什么以及如何将 XCHAR* 转换为 std::string。

如果有人愿意提供帮助,那将是非常友善的。

谢谢

最佳答案

我有一个头文件,它在 UTF8(用字母“a”表示)、UTF16(用字母“w”表示)和当前构建使用的任何内容(用字母“t”表示)之间转换).假设正如 chris 所说 XCHAR 与 TCHAR 相同,这些函数应该可以正常工作:

inline std::string wtoa(const std::wstring& Text){ 
    std::string s(WideCharToMultiByte(CP_UTF8, 0, Text.c_str(), Text.size(), NULL, NULL, NULL, NULL), '\0');
    s.resize(WideCharToMultiByte(CP_UTF8, 0, Text.c_str(), Text.size(), &s[0], s.size(), NULL, NULL));
    return s;
}
inline std::wstring atow(const std::string& Text) {
    std::wstring s(MultiByteToWideChar(CP_UTF8, 0, Text.c_str(), Text.size(), NULL, NULL), '\0');
    s.resize(MultiByteToWideChar(CP_UTF8, 0, Text.c_str(), Text.size(), &s[0], s.size()));
    return s;
}
#ifdef _UNICODE
inline std::string ttoa(const std::wstring& Text) {return wtoa(Text);}
inline std::wstring atot(const std::string& Text) {return atow(Text);}
inline const std::wstring& ttow(const std::wstring& Text) {return Text;}
inline const std::wstring& wtot(const std::wstring& Text) {return Text;}
typedef std::wstring tstring;
typedef std::wstringstream tstringstream;
#else    
inline const std::string& ttoa(const std::string& Text) {return Text;}
inline const std::string& atot(const std::string& Text) {return Text;}
inline std::wstring ttow(const std::string& Text) {return atow(Text);}
inline std::string wtot(const std::wstring& Text) {return wtoa(Text);}
typedef std::string tstring;
typedef std::stringstream tstringstream;
#endif

用法:

int main() {
    XCHAR* str = ///whatever
    std::string utf8 = ttoa(str);
    std::wstring utf16 = ttow(str);
}

请记住,其中一些返回可变右值,一些返回常量左值,但这在大多数代码中并没有您想象的那么严重。

关于c++ - 转换 xchar* std::string,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12358760/

相关文章:

c++ - 为什么协程的返回类型必须是可移动构造的?

c++ - RapidXML - 如何处理丢失的节点/值

c++ - 理解c++中的析构函数

c++ - 在 Visual Studio 项目中创建包含文件夹和 Lib 文件夹

c# - 如何将数据从 Windows 窗体应用程序发送到 Asp.Net Web 服务应用程序

c# - 为 amazon web services sdk 添加对 visual studio 项目的引用

c++ - 使用 mpl::if_、boost::function 和 typedef 无效的问题

c++ - 需要清除 C++ 组合框中的重复项

c# - 要使用多少线程?

visual-studio-2010 - 在Visual Studio 10 IronPython控制台消失之前,我无法读取错误