converting narrow string to wide string

Viewed 29045

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

I have tried this method :

string myName;
getline( cin , myName );
wstring printerName( L(myName) );  // error C3861: 'L': identifier not found
wchar_t* WprinterName = printerName.c_str(); // error C2440: 'initializing' : cannot convert from 'const wchar_t *' to 'wchar_t *'

But i get errors as listed above.

Why do i get these errors ? How can i fix them ?

Is there any other method of directly converting a narrow string to a wide string ?

9 Answers

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.

This article published on the MSDN Magazine 2016 September issue discusses the conversion in details using Win32 APIs.

Note that using MultiByteToWideChar() is much faster than using the std:: stuff on Windows.

Use mbtowc():

string myName;
wchar_t wstr[BUFFER_SIZE];

getline( cin , myName );
mbtowc(wstr, myName, BUFFER_SIZE);
Related