The question is how to convert wstring to string?
I have next example :
#include <string>
#include <iostream>
int main()
{
std::wstring ws = L"Hello";
std::string s( ws.begin(), ws.end() );
//std::cout <<"std::string = "<<s<<std::endl;
std::wcout<<"std::wstring = "<<ws<<std::endl;
std::cout <<"std::string = "<<s<<std::endl;
}
the output with commented out line is :
std::string = Hello
std::wstring = Hello
std::string = Hello
but without is only :
std::wstring = Hello
Is anything wrong in the example? Can I do the conversion like above?
EDIT
New example (taking into account some answers) is
#include <string>
#include <iostream>
#include <sstream>
#include <locale>
int main()
{
setlocale(LC_CTYPE, "");
const std::wstring ws = L"Hello";
const std::string s( ws.begin(), ws.end() );
std::cout<<"std::string = "<<s<<std::endl;
std::wcout<<"std::wstring = "<<ws<<std::endl;
std::stringstream ss;
ss << ws.c_str();
std::cout<<"std::stringstream = "<<ss.str()<<std::endl;
}
The output is :
std::string = Hello
std::wstring = Hello
std::stringstream = 0x860283c
therefore the stringstream can not be used to convert wstring into string.
In case anyone else is interested: I needed a class that could used interchangeably wherever either a
string
orwstring
was expected. The following classconvertible_string
, based on dk123's solution, can be initialized with either astring
,char const*
,wstring
orwchar_t const*
and can be assigned to by or implicitly converted to either astring
orwstring
(so can be passed into a functions that take either).As Cubbi pointed out in one of the comments,
std::wstring_convert
(C++11) provides a neat simple solution (you need to#include
<locale>
and<codecvt>
):I was using a combination of
wcstombs
and tedious allocation/deallocation of memory before I came across this.http://en.cppreference.com/w/cpp/locale/wstring_convert
update(2013.11.28)
One liners can be stated as so (Thank you Guss for your comment):
Wrapper functions can be stated as so: (Thank you ArmanSchwarz for your comment)
Note: there's some controversy on whether
string
/wstring
should be passed in to functions as references or as literals (due to C++11 and compiler updates). I'll leave the decision to the person implementing, but it's worth knowing.Note: I'm using
std::codecvt_utf8
in the above code, but if you're not using UTF-8 you'll need to change that to the appropriate encoding you're using:http://en.cppreference.com/w/cpp/header/codecvt