简体   繁体   中英

converting xchar* std::string

i recently came across a piece of c++ code which has a type XCHAR*. I was wondeing what this type is and how can i convert a XCHAR* to a std::string.

It would be very kind of someone to help.

Thanks

I have a header file I use that converts between UTF8 (denoted by the letter "a"), UTF16 (denoted by the letter "w"), and whatever the current build is using (denoted by the letter "t"). Assuming that as chris says that XCHAR is the same as TCHAR, these functions should work fine:

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

usage:

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

Keep in mind that some of these return a mutable rvalue, and some a const lvalue, but this is less of a problem than you'd think in most code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM