Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I convert wchar_t* to std::string?

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>'

like image 380
codefrog Avatar asked Dec 02 '10 21:12

codefrog


People also ask

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 STD string to Lpwstr?

std::wstring stemp = std::wstring(s. begin(), s. end()); LPCWSTR sw = stemp. c_str();

What is a Wstring C++?

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.


2 Answers

std::wstring ws( args.OptionArg() ); std::string test( ws.begin(), ws.end() ); 
like image 184
Ulterior Avatar answered Sep 21 '22 20:09

Ulterior


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.

like image 39
Praetorian Avatar answered Sep 22 '22 20:09

Praetorian