How do I convert a string to a wstring using the value of the string?

南楼画角 提交于 2019-12-04 19:24:42

Here is an implementation using wcstombs (Updated):

#include <iostream>
#include <cstdlib>
#include <string>

std::string wstring_from_bytes(std::wstring const& wstr)
{
    std::size_t size = sizeof(wstr.c_str());
    char *str = new char[size];
    std::string temp;

    std::wcstombs(str, wstr.c_str(), size);

    temp = str;
    delete[] str;

    return temp;
}

int main()
{
    std::wstring wstr = L"abcd";
    std::string str = wstring_from_bytes(wstr);
}

Here is a demo.

This is in reference to the most up-voted answer but I don't have enough "reputation" to just comment directly on the answer.

The name of the function in the solution "wstring_from_bytes" implies it is doing what the original poster wants, which is to get a wstring given a string, but the function is actually doing the opposite of what the original poster asked for and would more accurately be named "bytes_from_wstring".

To convert from string to wstring, the wstring_from_bytes function should use mbstowcs not wcstombs

#define _CRT_SECURE_NO_WARNINGS

#include <iostream>
#include <cstdlib>
#include <string>

std::wstring wstring_from_bytes(std::string const& str)
{
    size_t requiredSize = 0;
    std::wstring answer;
    wchar_t *pWTempString = NULL;

    /*
    * Call the conversion function without the output buffer to get the required size
    *  - Add one to leave room for the NULL terminator
    */
    requiredSize = mbstowcs(NULL, str.c_str(), 0) + 1;

    /* Allocate the output string (Add one to leave room for the NULL terminator) */  
    pWTempString = (wchar_t *)malloc( requiredSize * sizeof( wchar_t ));  
    if (pWTempString == NULL)  
    {  
        printf("Memory allocation failure.\n");  
    }
    else
    {
        // Call the conversion function with the output buffer
        size_t size = mbstowcs( pWTempString, str.c_str(), requiredSize);
        if (size == (size_t) (-1))  
        {  
            printf("Couldn't convert string\n");  
        }
        else
        {
            answer = pWTempString;
        }
    }


    if (pWTempString != NULL)
    {
        delete[] pWTempString;
    }

    return answer;
}

int main()
{
   std::string str = "abcd";
   std::wstring wstr = wstring_from_bytes(str);
}

Regardless, this is much more easily done in newer versions of the standard library (C++ 11 and newer)

#include <locale>
#include <codecvt>
#include <string>

std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;

std::wstring wide = converter.from_bytes(narrow_utf8_source_string);

printf-style format specifiers are not part of the C++ library and cannot be used to construct a string.

If the string may only contain single-byte characters, then the range constructor is sufficient.

std::string narrower( "hello" );
std::wstring wider( narrower.begin(), narrower.end() );

The problem is that we usually use wstring when wide characters are applicable (hence the w), which are represented in std::string by multibyte sequences. Doing this will cause each byte of a multibyte sequence to translate to an sequence of incorrect wide characters.

Moreover, to convert a multibyte sequence requires knowing its encoding. This information is not encapsulated by std::string nor std::wstring. C++11 allows you to specify an encoding and translate using std::wstring_convert, but I'm not sure how widely supported it is of yet. See 0x....'s excellent answer.

I found this function. Could not find any predefined method to do this.

std::wstring s2ws(const std::string& s)
{
    int len;
    int slength = (int)s.length() + 1;
    len = MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, 0, 0); 
    wchar_t* buf = new wchar_t[len];
    MultiByteToWideChar(CP_ACP, 0, s.c_str(), slength, buf, len);
    std::wstring r(buf);
    delete[] buf;
    return r;
}

std::wstring stemp = s2ws(myString);
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!