Skip to content

Instantly share code, notes, and snippets.

@danzek
Created April 13, 2017 21:48
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danzek/d6a0e4a48a5439e7f808ed1497f6268e to your computer and use it in GitHub Desktop.
Save danzek/d6a0e4a48a5439e7f808ed1497f6268e to your computer and use it in GitHub Desktop.
Converting between wstring and string in C++
/* Retrieved from http://stackoverflow.com/a/18374698/ on April 13, 2017
* Posted by user [dk123](https://stackoverflow.com/users/1709725/dk123) on Aug 22 '13 at 7:57
* Credit given in post to user ArmanSchwarz who posted a comment with this information
*/
#include <codecvt>
// string to wstring
wstring s2ws(const std::string& str)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.from_bytes(str);
}
// wstring to string
string ws2s(const std::wstring& wstr)
{
using convert_typeX = std::codecvt_utf8<wchar_t>;
std::wstring_convert<convert_typeX, wchar_t> converterX;
return converterX.to_bytes(wstr);
}
@danzek
Copy link
Author

danzek commented Sep 5, 2022

Wow, thank you! This is very helpful.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment