format/printutf8.cpp

The following code example is taken from the book
C++23 - The Complete Guide by Nicolai M. Josuttis, Leanpub, 2026
The code is licensed under a Creative Commons Attribution 4.0 International License. Creative Commons License

// raw code

// - compile with VC++:
// cl /O2 /std:c++latest /EHsc /utf-8 utf8.cpp
#include <iostream>
#include <format>
#include <print>

int main()
{
  // use "Köln 100€" as UTF-8 string literal with Unicode:
  constexpr const char* data = "K\u00F6ln 100\u20AC";

  // print the value of each character:
  std::println("hex  dec  char");
  std::println("--------------");
  for (auto p = data; *p != '\0'; ++p) {
    std::println(" {0:2X}  {0:3d}  '{0}'", *p);
  }
  std::println("");

  std::cout << "** << and format():\n";  
  std::cout << data << '\n';                // might print garbage (on Windows)
  std::cout << std::format("{}\n", data);   // might print garbage (on Windows)
  std::cout << "** print() and println():\n";
  std::print("{}\n", data);                 // prints "Köln 100€"
  std::println(data);                       // prints "Köln 100€"
}