How can I convert a wstring to a string in C ? Consider the following 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; }
With the commented-out line, the output is:
std::string = Hello std::wstring = Hello std::string = Hello
However, without it, the output is only:
std::wstring = Hello
As pointed out by Cubbi, std::wstring_convert provides an easy solution:
#include <locale> #include <codecvt> std::wstring string_to_convert; using convert_type = std::codecvt_utf8<wchar_t>; std::wstring_convert<convert_type, wchar_t> converter; // Convert wstring to string std::string converted_str = converter.to_bytes(string_to_convert);
You can also use helper functions to simplify the conversion:
// Convert string to wstring std::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); } // Convert wstring to string std::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); }
The above is the detailed content of How can I efficiently convert a `wstring` to a `string` in C ?. For more information, please follow other related articles on the PHP Chinese website!