Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conversion of wchar_t* to string [duplicate]

How can I convert an wchar_t* array to an std::string varStr in win32 console.

like image 972
AnasShoaib90 Avatar asked Dec 31 '14 11:12

AnasShoaib90


People also ask

How do I convert a number to a string in C++?

The next method in this list to convert int to string in C++ is by using the to_string() function. This function is used to convert not only the integer but numerical values of any data type into a string. The to_string() method is included in the header file of the class string, i.e., <string> or <cstring>.

What is a wchar_t in C++?

The wchar_t type is an implementation-defined wide character type. In the Microsoft compiler, it represents a 16-bit wide character used to store Unicode encoded as UTF-16LE, the native character type on Windows operating systems.

How do you convert Wstring to Tchar?

So depending on your compilation configuration, you can convert TCHAR* to string or wstring. To use UNICODE character set, click Project->Properties->Configuration Properties->General->Character Set, and then select "Use Unicode Character Set".

What is Wstring?

Wide string. String class for wide characters. This is an instantiation of the basic_string class template that uses wchar_t as the character type, with its default char_traits and allocator types (see basic_string for more info on the template).


2 Answers

Use wstring, see this code:

// Your wchar_t*
wchar_t* txt = L"Hello World";
wstring ws(txt);
// your new String
string str(ws.begin(), ws.end());
// Show String
cout << str << endl;
like image 73
FelipeDurar Avatar answered Oct 17 '22 13:10

FelipeDurar


You should use the wstring class belonging to the namespace std. It has a constructor which accepts a parameter of the type wchar_t*.

Here is a full example of using this class.

wchar_t* characters=L"Test";
std::wstring string(characters);

You do not have to use a constructor containing String.begin() and String.end() because the constructor of std::wstring automatically allocates memory for storing the array of wchar_t and copies the array to the allocated memory.

like image 9
Norbert Willhelm Avatar answered Oct 17 '22 11:10

Norbert Willhelm