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 .
70
Upvotes
View all comments
Show parent comment
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, andstd::format, has some other lib support, and can handle bad non-unicode filenames on Windows.Too bad it's not quite the
char8_tideal.