converting narrow string to wide string

前端 未结 9 1493
难免孤独
难免孤独 2020-12-06 11:57

How can i convert a narrow string to a wide string ?

I have tried this method :

string myName;
getline( cin , myName );
wst         


        
相关标签:
9条回答
  • 2020-12-06 12:58

    The Windows API provides routines for doing this: WideCharToMultiByte() and MultiByteToWideChar(). However, they are a pain to use. Each conversion requires two calls to the routines and you have to look after allocating/freeing memory and making sure the strings are correctly terminated. You need a wrapper!

    I have a convenient C++ wrapper on my blog, here, which you are welcome to use.

    0 讨论(0)
  • 2020-12-06 13:02

    ATL (non-express editions of Visual Studio) has a couple useful class types which can convert the strings plainly. You can use the constructor directly, if you do not need to hold onto the string.

    #include <atlbase.h>
    
    std::wstring wideString(L"My wide string");
    std::string narrowString("My not-so-wide string");
    
    ATL::CW2A narrow(wideString.c_str()); // narrow is a narrow string
    ATL::CA2W wide(asciiString.c_str()); // wide is a wide string
    
    0 讨论(0)
  • 2020-12-06 13:02

    The original question of this thread was: "How can i convert a narrow string to a wide string?"

    However, from the example code given in the question, there seems to be no conversion necessary. Rather, there is a compiler error due to the newer compilers deprecating something that used to be okay. Here is what I think is going on:

        // wchar_t* wstr = L"A wide string";     // Error: cannot convert from 'const wchar_t *' to 'wchar_t *'
    
    wchar_t const* wstr = L"A wide string";             // okay
    const wchar_t* wstr_equivalent = L"A wide string";  // also okay
    

    The c_str() seems to be treated the same as a literal, and is considered a constant (const). You could use a cast. But preferable is to add const.

    The best answer I have seen for converting between wide and narrow strings is to use std::wstringstream. And this is one of the answers given to C++ Convert string (or char*) to wstring (or wchar_t*)

    You can convert most anything to and from strings and wide strings using stringstream and wstringstream.

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