1

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.

spaL
  • 604
  • 7
  • 21
  • What encoding do your wide strings have, and what encoding do you want in your byte strings? – Caleth Oct 26 '21 at 08:13
  • wide strings have UTF-16, the encoding I want in my byte strings is UTF-8 – spaL Oct 26 '21 at 08:17
  • What are the "solutions" you have seen? What have you tried yourself? What problems (if any) do you have with your attempt? – Some programmer dude Oct 26 '21 at 09:01
  • Mainly from these two pages: and . I've tried using sprintf, which causes a buffer overflow. I've tried using _bstr_t, but I can't seem to get to work. I've heard about but apparently some functionality has been deprecated since C++17. – spaL Oct 26 '21 at 11:32

1 Answers1

0

As far as I know, 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';
}
alex_noname
  • 26,459
  • 5
  • 69
  • 86
  • 1
    How do I determine what the size of the char buffer has to be? – spaL Oct 26 '21 at 08:21
  • 1
    If `dst` is `nullptr`, the number of characters required to convert the wide-character string is returned. – alex_noname Oct 26 '21 at 08:26
  • @alex_noname It's a POSIX extension of the standard. Fortunately the MSVC implementation works the same, but care should still be taken if true portability is needed. – Some programmer dude Oct 26 '21 at 09:04
  • Is there any other way to get the number of characters required or is this the only way? – spaL Oct 26 '21 at 11:33
  • I don’t know of any other convenient enough way to do this. But you can use [wcsrtombs](https://en.cppreference.com/w/cpp/string/multibyte/wcsrtombs), its behavior when `dst == nullptr` is standardized. – alex_noname Oct 26 '21 at 11:50