I changed my class to use std::string (based on the answer I got here but a function I have returns wchar_t *. How do I convert it to std::string?
I tried this:
std::string test = args.OptionArg();
but it says error C2440: 'initializing' : cannot convert from 'wchar_t *' to 'std::basic_string<_Elem,_Traits,_Ax>'
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.
std::wstring stemp = std::wstring(s. begin(), s. end()); LPCWSTR sw = stemp. c_str();
This function is used to convert the numerical value to the wide string i.e. it parses a numerical value of datatypes (int, long long, float, double ) to a wide string. It returns a wide string of data type wstring representing the numerical value passed in the function.
std::wstring ws( args.OptionArg() ); std::string test( ws.begin(), ws.end() );
You can convert a wide char string to an ASCII string using the following function:
#include <locale> #include <sstream> #include <string> std::string ToNarrow( const wchar_t *s, char dfault = '?', const std::locale& loc = std::locale() ) { std::ostringstream stm; while( *s != L'\0' ) { stm << std::use_facet< std::ctype<wchar_t> >( loc ).narrow( *s++, dfault ); } return stm.str(); }
Be aware that this will just replace any wide character for which an equivalent ASCII character doesn't exist with the dfault
parameter; it doesn't convert from UTF-16 to UTF-8. If you want to convert to UTF-8 use a library such as ICU.
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