Wide narrow characters

What is the cleanest way to convert std :: wstring to std :: string? I used W2A and other macros in the past, but I never loved them.

+4
source share
6 answers

The most common way is std::ctype<wchar_t>::narrow() , but it does a little more than std :: copy as suggested by gishu, and you still need to manage your buffers.

If you are not trying to make any translation, but want only one-line, you can do std::string my_string( my_wstring.begin(), my_wstring.end() ) .

If you need the actual code translation, you can use locales / codecvt or one of the libraries from the other answer, but I assume that is not what you are looking for.

+2
source

Whatever you are looking for, icu , an open source library, a cross-platform library for working with Unicode and legacy encodings among many others.

+5
source

If the encoding in wstring is UTF-16 and you want to convert to UTF-8 encoded string, you can use the UTF8 CPP library:

 utf8::utf16to8(wstr.begin(), wstr.end(), back_inserter(str)); 
+2
source

See if that helps. To achieve your goal, std :: copy is used.

http://www.codeguru.com/forum/archive/index.php/t-193852.html

+1
source

I don't know if this is the โ€œcleanestโ€, but I used the copy () function without any problems.

 #include <iostream> #include <algorithm> using namespace std; string wstring2string(const wstring & wstr) { string str(wstr.length(),' '); copy(wstr.begin(),wstr.end(),str.begin()); return str; } wstring string2wstring(const string & str) { wstring wstr(str.length(),L' '); copy(str.begin(),str.end(),wstr.begin()); return wstr; } 

http://agraja.wordpress.com/2008/09/08/cpp-string-wstring-conversion/

+1
source

Since this is one of the first C ++ narrow-string search results, and it is before C ++ 11, here is a way to solve this problem in C ++ 11:

 #include <codecvt> #include <locale> #include <string> std::string narrow( const std::wstring& str ){ std::wstring_convert< std::codecvt_utf8_utf16< std::wstring::value_type >, std::wstring::value_type > utf16conv; return utf16conv.to_bytes( str ); } 
+1
source

All Articles