Multiplatform way to convert between std::string and std::wstring
boost, c++
Solution
Basically using the `<cstdlib>` you can get away with a similar implementation to what you already have, as mentioned by Joachim Pileborg. As long as you have set the locale to whatever you want it to be (for example: `setlocale( LC_ALL, "en_US.utf8" );`
`MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0)` => `mbstowcs(nullptr, data(str), size(str))`
`MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed)` => `mbstowcs(data(wstrTo), data(str), size(str))`
`WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL)` => `wcstombs(nullptr, data(wstr), size(wstr))`
`WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL)` => `wcstombs(data(strTo), data(wstr), size(wstr))`
EDIT:
c++11 requires strings to be allocated contiguously, which may be important if you are compiling cross-platform as previous standards did not require `string` to be allocated contiguously. Previously calling `&str[0]`, `&strTo[0]`, `&wstr[0]`, or `&wstrTo[0]` could have caused problems. Since c++17 is now the accepted standard, I've improved my suggested substitutions to use `data` rather than dereferencing the front of the strings.
Problem
I am currently using the methods `MultiByteToWideChar` and `WideCharToMultiByte` of the Windows API to convert between `std::string` and `std::wstring`. I am 'multiplatforming' my code removing Windows dependencies, so I would like to know alternative to the methods above. Concretely, using boost will be great. Which methods may I use? Here is the code I am currently using: ``` const std::wstring Use::stow(const std::string& str) { if (str.empty()) return L""; int size_needed = MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), NULL, 0); std::wstring wstrTo( size_needed, 0 ); MultiByteToWideChar(CP_UTF8, 0, &str[0], (int)str.size(), &wstrTo[0], size_needed); return wstrTo; } const std::string Use::wtos(const std::wstring& wstr) { if (wstr.empty()) return ""; int size_needed = WideCharToMultiByte(CP_UTF8, 0, &wstr[0], (int)wstr.size(), NULL, 0, NULL, NULL); std::string strTo( size_needed, 0 ); WideCharToMultiByte (CP_UTF8, 0, &wstr[0], (int)wstr.size(), &strTo[0], size_needed, NULL, NULL); return strTo; } ```