How to convert std:string to CString in unicode project

前端 未结 4 1446
盖世英雄少女心
盖世英雄少女心 2020-12-09 19:06

I have a std::string. I need to convert this std:string to a Cstring.

I try to use the .c_str() but it\'s only fo

相关标签:
4条回答
  • 2020-12-09 19:14

    Bonus: if you use the conversion frequently you can define a macro:

    #define STDTOCSTRING(s) CString(s.c_str())
    

    so your code is more readable.

    0 讨论(0)
  • 2020-12-09 19:15

    Unicode CString's constructor accepts char* so you can do this:

    std::string str = "string";
    CString ss(str.c_str());
    
    0 讨论(0)
  • 2020-12-09 19:17

    Use the ATL conversion macros. They work in every case, when you use CString. CString is either MBCS or Unicode... depends on your Compiler Settingss.

    std::string str = "string";
    CString ss(CA2T(str.c_str());
    
    0 讨论(0)
  • 2020-12-09 19:21

    CString has a conversion constructor taking a const char* (CStringT::CStringT). Converting a std::string to a CString is as simple as:

    std::string stdstr("foo");
    CString cstr(stdstr.c_str());
    

    This works for both UNICODE and MBCS projects. If your std::string contains embedded NUL characters you have to use a conversion constructor with a length argument:

    std::string stdstr("foo");
    stdstr += '\0';
    stdstr += "bar";
    CString cstr(stdstr.c_str(), stdstr.length());
    

    Note that the conversion constructors implicitly use the ANSI code page of the current thread (CP_THREAD_ACP) to convert between ANSI and UTF-16 encoding. If you cannot (or do not want to) change the thread's ANSI code page, but still need to specify an explicit code page to use for the conversion, you have to use another solution (e.g. the ATL and MFC String Conversion Macros).

    0 讨论(0)
提交回复
热议问题