r/cpp • • Sep 20 '26

Printing UTF-8 strings since C++23

C++23 provides significant better support to print UTF-8 strings.

For example:

std::string s = "K\u00F6ln: 100\u20AC";  // string ö and €
 
std::println("{}", s);        // prints "Köln 100€" 

// print hexadecimal code units (bytes of the UTF-8 string): 
std::vector<char> v{std::from_range, s};
std::println("{:n:X}", v);    // prints 4B, C3, B6, 6C, 6E, 3A, 20, 31, 30, 30, E2, 82, AC 

// new format specifier to interpret array of char as string:
std::println("{:?s}", v);     // prints "Köln 100€" 

This even works fine on Windows platforms (using I/O streams or std::format() might print garbage with a native Windows compiler on a native Windows platform).

See sections 3.2.3 and 4.3.3 of www.cppstd23.com .

68 Upvotes

36 comments sorted by

33

u/Tathorn Sep 20 '26

The problem isn't C++, but that the default windows terminal isn't set up for unicode. C++23 didn't "add support", it just made someone add a switch. Io streams could add that switch too, but they aren't going to touch that code.

7

u/UnusualPace679 Sep 21 '26 edited Sep 21 '26

C++23 adds support for std::vprint_unicode which is required to output the string via "a native Unicode API" (on Windows this means WriteConsoleW) if needed. There's no such requirement on iostream.

3

u/fdwr fdwr@github 🔍 Sep 21 '26 edited Sep 21 '26

Windows this means WriteConsoleW

The biggest remaining inconvenience of std::vprint_unicode on Windows is that it doesn't directly take a std::wstring_view, even though most of the strings you're dealing with when interacting with the Windows API is UTF-16. So, you have to allocate extra intermediates and convert your L"string" from UTF-16 -> UTF-8 first. I've found that just using std::format (which does directly accept std::wformat_string) or wprintf works more cleanly for most Windows text, and then for any text that is already UTF-8, I call SetConsoleOutputCP(CP_UTF8) on process startup, and add the PE manifest attribute <windowsSettings><activeCodePage>UTF-8</activeCodePage></windowsSettings> to catch other stragglers like std::filesystem::path::string() which would otherwise result in "???"s for non-ANSI characters.

2

u/qalmakka Sep 21 '26

yes but by using format + wprintf you're allocating a bunch of strings, unless you start formatting to buffers, etc. it's a PITA

3

u/fdwr fdwr@github 🔍 Sep 21 '26

Does std::print allocate temporaries internally? I'd rather not have 2 steps (format followed by writing to the console), which is why I'd like print to just work directly.

2

u/qalmakka Sep 21 '26

It's not supposed to, usually, unless a formatter is allocating inside

3

u/Tathorn Sep 21 '26

Not supposed to, but the MSVC STL does :/

1

u/cristi1990an ++ Sep 24 '26

1

u/Tathorn Sep 24 '26

True, nothing in the standard explicitly says not to. It would just be surprising. Like how std::print formats to a string first and then writes it to the stream, even though there's no reason why it couldn't have just written to the stream to begin with.

I'm coming at this because I have written my own fmt library, without needing these temporaries. Perhaps its the limitations std::format places on the developers that force this to be hard to optimize.

1

u/cristi1990an ++ Sep 24 '26

Do note that it actually doesn't format to an intermediary buffer (or at least the non locking optimization adopted by the standard now allows the implementation not to). Check the latest STL implementations.

→ More replies

1

u/cristi1990an ++ Sep 24 '26 edited Sep 24 '26

What do you mean it's "not supposed to"? There's nothing in the standard saying that. If anything it's quite the opposite, If a formatted type doesn't support non-locking optimization and it's formatting size is too big for any stack buffer the implementation uses (which in itself is not mandated) it will allocate. This is what MSVC and libstdc++ do. libc++ is worse since it hasn't implemented any non-locking optimization yes so it allocates intermediary strings all the time.

2

u/cristi1990an ++ Sep 24 '26

Depends on the implementation. Any type format specifier can allocate internally. In theory std::print in itself could avoid additional temporary allocations as long as all formatted type support the non-locking optimization. MSVC and libstdc++ implement this optimization though MSVC *tehnically* might need additional allocations when converting to a wchar_t buffer but that's more of a Windows specific issue.

1

u/Jardik2 Sep 24 '26

Just wait when you realize that windows paths are not always valid utf16. 

5

u/SFGrenade Sep 21 '26

me when std::u8string

19

u/fortsnek274 Sep 20 '26

Only in that it specially handles the console. This modern language still can't print it's own UTF-8 type.

29

u/aearphen {fmt} Sep 20 '26

Most languages such as Java actually fail to print Unicode correctly to console on Windows. Notable exception is Rust which does the same thing as C++ here. This has nothing to do with types but with the fact that Windows uses multiple (sometimes incompatible) legacy encodings.

11

u/fortsnek274 Sep 20 '26

Yes, the Windows console is a frail piece of ancient technology sometimes. At least Windows Terminal is better. And that magic incantation can fix output.

But the type problem is universal. You just can't use charN_t/uNstring everywhere in a standard C++ program because the std lib doesn't support it.

2

u/aearphen {fmt} Sep 20 '26

charN_t types are indeed not supported anywhere but they are also not needed for portable Unicode support as we can see from Nico's example.

8

u/fortsnek274 Sep 20 '26

Not needed? Of course. You don't need std::print either.

But these types exist. So they should be supported. Preferably for more than just the unicode transcoding paper.

These types also declare the encoding of your strings strictly. Type safety. Not leaving it up to "execution encoding" nonsense. Also interacting better with std::filesystem::path.

1

u/aearphen {fmt} Sep 20 '26

Standard has a lot of old problematic types like std::locale. It doesn't mean that they need to be supported. The world mostly moved on to the UTF-8 char so none of this matters. I also made formatting of std::filesystem::path work correctly with Unicode without any need for charN_t.

6

u/fortsnek274 Sep 20 '26

Yeah, I want to move onto UTF-8 too. But I'm stuck with this type-unsafe nonsense and a near-useless type-safe alternative. It's bad language design.

You wouldn't say this about well-designed languages like python. You have your unicode string type, you can print it directly, input it directly, paths convert with it, files have strict encoding, binary is a separate type, and the string type has unicode utilities. How things should be. What you'd probably get if there was a C++2.

But sure, you don't need it. You can just continue to write silly code to work around language/lib deficiencies.

3

u/rdtsc Sep 20 '26

You're shouting into the wind here (and I very much agree with you). People have misused char for UTF-8 for a long time even though it's neither portable, robust, nor really usable (many standard lib functions don't even work with with multibyte encodings) because they can't be bothered to convert their strings. Which is funnily always expected of you when you come with Windows and UTF-16.

4

u/azswcowboy Sep 21 '26

It is being worked on and is acknowledged by the committee as a significant issue to resolve.

https://github.com/bemanproject/utf_view

2

u/fortsnek274 Sep 20 '26

Ah, the great type safety of wstring. The compiler makes you convert. Which was great when refactoring a lib. The typing easily distinguishes between text strings and internal strings.

And wstring kind of works with wcout , wcin, and std::format, has some other lib support, and can handle bad non-unicode filenames on Windows.

Too bad it's not quite the char8_t ideal.

0

u/GabiTheProgrammer Sep 20 '26

How do other languages do it?

7

u/fortsnek274 Sep 20 '26

With a print statement. Or rather, they don't have to do anything because a half functioning system of string types seems to be a C++ speciality.

12

u/mort96 Sep 20 '26

What was wrong with cout/cerr, I've been printing UTF-8 to those forever

17

u/RudeSize7563 Sep 20 '26

std::cout is platform agnostic so it will just send the raw bytes, in the other side std::print is required by the standard to use platform specific functionality when necessary to display the expected results. Also std::print can align emojis and in general has more awareness of the expected width on screen of a sequence of combining code points.

3

u/jombrowski Sep 20 '26

What if I don't have a printer?

7

u/eisenwave WG21 Member Sep 21 '26

You print to PDF.

1

u/cristi1990an ++ Sep 24 '26

Some shameless self-promoting of my unicode library since we're taling about this: https://github.com/cristi1990an/unicode_ranges

1

u/Bruce-Wshin Sep 21 '26

how to use printf to format all of these

-1

u/YouNeedDoughnuts Sep 20 '26

That's good to know. I have an app on C++17 which makes extensive use of unicode, and I've been loathe to upgrade to C++20 because of the poor design changes around Unicode strings, despite the benefits which std::span and the "bit" header would bring.

15

u/aearphen {fmt} Sep 20 '26

For older systems you could also use {fmt} which provides portable Unicode support and only requires C++11.