Dejwi
Dejwi

Reputation: 4487

Best way to fill wstring with const char*

I have to "translate" a:

char data[32]

into a:

tstring data;

Where the tstring is a typedef to std::string or a std::wstring depending on a preprocessor definition.

Assuming that data[32] contains only ASCII characters, what whould be the easiest way to pass this data into a tstring object?

Upvotes: 3

Views: 6965

Answers (2)

Rudolfs Bundulis
Rudolfs Bundulis

Reputation: 11934

Since you don't need to do any character conversions you could initialize both of the strings from with a vector of characters. Consider this example:

#include <string>
#include <vector>

int main()
{
    char data[32];
    std::vector<char> v(data, data + 32);
    std::string str(v.begin(), v.end());
    std::wstring wstr(v.begin(), v.end());
}

Upvotes: 7

Simon Kraemer
Simon Kraemer

Reputation: 5680

EDIT: The temporary std::string is not needed. I have updated my answer with an example.

See here: C++ Convert string (or char*) to wstring (or wchar_t*)

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

#define XWSTRING

#ifdef XWSTRING
typedef std::wstring xstring;
#else 
typedef std::string xstring;
#endif

xstring initString(const char* data)
{
#ifdef XWSTRING
    static std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
    return xstring(converter.from_bytes(data));
#else
    return xstring(data);
#endif
}


int main()
{
    char in_data[32] = "HELLO WORLD";
    xstring out_data = initString(in_data);
}

Upvotes: 2

Related Questions