r/cpp • u/NicoJosuttis • 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
View all comments
Show parent comment
8
u/fortsnek274 Sep 20 '26
Not needed? Of course. You don't need
std::printeither.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.