lib/spanstream.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 <print>
#include <spanstream>

int main()
{
  char buf[20]{};     // braces to initialize buf with null terminators

  // span stream for reading and writing from/to buf (except last null terminator):
  std::spanstream spStrm{{buf, sizeof(buf)-1}};

  // write values as long as possible:
  std::print("write:");
  for (int i = 0; spStrm; ++i) {
    auto val = i * 7.7;
    std::print(" {}", val);
    spStrm << val << ' ';
  }
  std::println("\nbuf:   {}", buf);

  spStrm.clear();     // clear fail bit

  // read values as long as possible:
  std::print("read: ");
  while (spStrm) {
    double d;
    spStrm >> d;
    if (spStrm) {
      std::print(" {:.1f}", d);
    }
  }
}