2012-09-10 137 views
0

我最近遇到了一块C++代码,它有一个类型XCHAR *。我想知道这是什么类型,我如何将XCHAR *转换为std :: string。转换xchar * std :: string

这将是非常善良的人来帮助。

感谢

+2

从'XCHAR'和'TCHAR'相同的位置寻找。因此,您需要一个'std :: string'或'std :: wstring',具体取决于它应该是哪个,构造函数应该采用它。 – chris

回答

1

我有一个头文件我用的UTF8,UTF16(用字母表示“W”)(由字母“A”表示)之间的转换,不管当前构建使用(记由字母“t”)。假设克里斯说,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); 
} 

记住其中的一些返回一个可变的右值,有的一常量左值,但这比在大多数代码中想象的要少。