Convert wchar_t to string?

Stuvolas picture Stuvolas · May 24, 2011 · Viewed 18.7k times · Source

I have a wchar_t I'd like to convert to a string. The string should then be read using stringstream. I have looked converting it over here: http://msdn.microsoft.com/en-us/library/ms235631(v=vs.80).aspx but none of them return anything useable with stringstream. I'm not very experienced with coding so I'm probably missing something really simple.

Thanks in advance!

Answer

Dennis picture Dennis · May 24, 2011

If you do actually need a string from a wchar_t* then you will first need to convert the wchar_t* to a char*. There are various methods to do this depending on what compiler you are using. The simplest way is to use wcstombs() but there are caveats with that. Here is a good discussion on the matter, with some solutions that might inspire you http://www.daniweb.com/software-development/cpp/threads/87362.

However you can just use wstring directly with wchar_t* as @Space_C0wb0y has mentioned. If that is what you are looking for please mark his answer as correct.