STRING & WSTRING, char and wchar_t

I am new to c++, and I am trying to convert a std::string to a std::wstring

I am using this function:

1
2
3
4
5
6
7
8
wstring widen( const string& str )
{
	wostringstream wstm ;
	const ctype<wchar_t> & ctfacet = use_facet< ctype<wchar_t> >( wstm.getloc() ) ;
	for( size_t i=0 ; i<str.size() ; ++i )
	wstm << ctfacet.widen( str[i] ) ;
	return wstm.str() ;
}


Now, when I try to do this:

1
2
3
string s("the url of a website");
wstring ws = widen(s);
cout << ws.c_str() << endl;


I get output that looks like this:

00114E60

WHAT IS GOING ON?! why won't it transfer the text stored in "s" to "ws"? Am I missing something? the function "widen()" does not return an address, it returns the wstring object, so.... shouldn't this work? Please help me. How do I convert from string to wstring?

Also, whats the big diff between char and wchar_t?
I had to this in one of my last programs and I used this code:

1
2
3
4
5
std::wstring _stringToWstring(const std::string &strPicPath) {
	std::wstring temp(strPicPath.length(), L' ');
	std::copy(strPicPath.begin(), strPicPath.end(), temp.begin());
	return temp;
}
The problem is that there's no overload of operator<<() that takes a wchar_t * (which is what std::wstring::c_str() returns) as an argument. There's no simple way of outputting wide strings in C++. std::wcout tends to screw up characters >0x7F, defeating the point of the conversion. Writing the binary layout to a file is unportable. Converting to UTF-8 before outputting works very well, but you have to provide the UTF-8 conversion function yourself, be it through a library or your own implementation.

I'd use mcleano's code, by the way. It's much clearer and you don't lose any behavior (std::string -> std::wstring is really just an element by element copy). It's probably faster, too.
Topic archived. No new replies allowed.