gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 07:57:35 25 4
gpt4 key购买 nike

我最近遇到了一段类型为 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com