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

user2619824 picture user2619824 · Aug 15, 2013 · Viewed 7.7k times · Source

I'm new to C++ and I have this issue. I have a string called DATA_DIR that I need for format into a wstring.

string str = DATA_DIR;
std::wstring temp(L"%s",str); 

Visual Studio tells me that there is no instance of constructor that matches with the argument list. Clearly, I'm doing something wrong.

I found this example online

std::wstring someText( L"hello world!" );

which apparently works (no compile errors). My question is, how do I get the string value stored in DATA_DIR into the wstring constructor as opposed to something arbitrary like "hello world"?

Answer

0x499602D2 picture 0x499602D2 · Aug 15, 2013

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.