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

View all comments

Show parent comment

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.

1

u/Tathorn Sep 24 '26

I still see them writing to a string first, and then the stream. Even when there's no formatting args, it has to do an _Unescape_braces into a string.

2

u/cristi1990an ++ Sep 24 '26

Oh, OK. That's interesting. It seems like this is done only for strings with no formatting arguments. Seems like a bit of an optimization oversight. You gave me an idea for a contribution here

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.