How do I place strings like 'char32_t' and 'char16_t' on the console in C++?

Asked

Viewed 47 times

0

New C++17 added characters char32_t and char16_t, added also 'u16string' and 'u32string', but did not create any way to put them on the console screen.

For example:

int main()
{
    std::u16string u16s{ u"meu teste" }; //até aqui tudo bem.
    std::cout << u16s << std::endl; //não compila, std::cout não aceita u16string
    //não existe std::u16cout nem std::u32cout como existe std::wcout 
}
  • 1

    Tried to use wcout?

  • yeah, I tried that

1 answer

0


The way for now is to use the classes std::codecvt_utf8_utf16 and std::wstring_convert (although discontinued in ) to convert a string to UTF-16 for UTF-8:

#include <iostream>
#include <locale>
#include <codecvt>
#include <string>

int main()
{
    std::u16string u16str = u"meu teste";
    std::wstring_convert<std::codecvt_utf8_utf16<char16_t>, char16_t> codecvt;
    std::string u8str = codecvt.to_bytes(u16str);
    std::cout << u8str << '\n';
}

With the discontinuation of these classes, it is not possible to convert using only the standard library. However, there is a new unicode study group on the C++committee. We will probably see new Apis for this type of language work.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.