converting narrow string to wide string

前端 未结 9 1507
难免孤独
难免孤独 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 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.

提交回复
热议问题