format/printfile.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

#include <iostream>  // for std::cerr
#include <print>
#include <string>
#include <vector>
#include <fstream>

int main()
{
  std::string filename = "tmp.txt";
  std::ofstream file{filename};
  if (!file) {
    std::println(std::cerr, "cannot open '{}'", filename);
    return 1;
  }

  // write the elements of a collection into the opened file:
  std::vector<std::string> coll{"Rio", "Tokyo", "Kiev"};
  for (const auto& elem : coll) {
    std::println(file, "City: {}", elem);   // formatted output into a file
  }
}