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

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.