views:

177

answers:

6

What is the cleanest way of converting a std::wstring into a std::string? I have used W2A et al macros in the past, but I have never liked them.

+1  A: 

See if this helps. This one uses std::copy to achieve your goal.

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

Gishu
But it does nothing more than invoke the implicit conversion from `wchar_t` to `char`, which is basically an assignment of the integer value. It only works for the characters that exist in both encodings, and have the same representation in both.
jalf
Well to convert from A to B, there must be an equivalent of A in the domain of B. There must exist a mapping.. not clear on what you mean by "same representation in both".
Gishu
+1  A: 

Perhaps boost::lexical_cast is what you look for.

For compilers with full language and library support for wide characters, lexical_cast now supports conversions from wchar_t, wchar_t *, and std::wstring and to wchar_t and std::wstring.

See: lexical_cast

Polybos
+3  A: 

What you might be looking for is icu, an open-source, cross-platform library for dealing with Unicode and legacy encodings amongst many other things.

bmargulies
Thank you, this will be useful in other projects.
DanDan
+1  A: 

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

If you're not trying to perform any translation but just want a one-liner, you can do std::string my_string( my_wstring.begin(), my_wstring.end() ).

If you want actual encoding translation, you can use locales/codecvt or one of the libraries from another answer, but I'm guessing that's not what you're looking for.

Potatoswatter
The one liner worked fine in this case. Thanks!
DanDan
+1  A: 

I don't know if it's the "cleanest" but I've used copy() function without any problems so far.

#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/

Graphics Noob
Standard coding practice note: you make one extra copy of each string when passing parameters by value - pass them by const reference instead.
Nikolai N Fetissov
good catch Nikolai, I'll update
Graphics Noob
+1  A: 

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

utf8::utf16to8(wstr.begin(), wstr.end(), back_inserter(str));
Nemanja Trifunovic
Thank you, I like the look of this.
DanDan