How can I convert an wchar_t*
array to an std::string
varStr in win32 console.
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>.
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.
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".
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).
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;
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With