简体   繁体   中英

Converting wchar_t * to char * in C++20

Currently using WSL2 Ubuntu, G++20.

What are some recommended ways to convert wchar_t * to char * in C++20? I have seen similar posts created several years ago, but I wasn't sure if they were still viable as a solution or if they were deprecated.

If I'm not mistaken wcstombs (and wcsrtombs ) is still relevant in C++ 20:

#include <iostream>
#include <clocale>
#include <cstdlib>
 
int main()
{
    std::setlocale(LC_ALL, "en_US.utf8");
    // UTF-8 narrow multibyte encoding
    const wchar_t* wstr = L"z\u00df\u6c34\U0001d10b"; // or L"zß水𝄋"
    char mbstr[11];
    std::wcstombs(mbstr, wstr, 11);
    std::cout << "multibyte string: " << mbstr << '\n';
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM