saplingPro saplingPro - 1 year ago 181
C++ Question

converting narrow string to wide string

How can i convert a narrow

to a wide

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
string to a
string ?

Answer Source

You should do this :

inline std::wstring convert( const std::string& as )
            // deal with trivial case of empty string
    if( as.empty() )    return std::wstring();

            // determine required length of new string
    size_t reqLength = ::MultiByteToWideChar( CP_UTF8, 0, as.c_str(), (int)as.length(), 0, 0 );

            // construct new string of required length
    std::wstring ret( reqLength, L'\0' );

            // convert old string to new string
    ::MultiByteToWideChar( CP_UTF8, 0, as.c_str(), (int)as.length(), &ret[0], (int)ret.length() );

            // return new string ( compiler should optimize this away )
    return ret;

This expects the std::string to be UTF-8 (CP_UTF8), when you have another encoding replace the codepage.

Another way could be :

inline std::wstring convert( const std::string& as )
    wchar_t* buf = new wchar_t[as.size() * 2 + 2];
    swprintf( buf, L"%S", as.c_str() );
    std::wstring rval = buf;
    delete[] buf;
    return rval;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download