lib/ospanstream3.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()
{
  // fix-sized buffer initialized with 10 '?' and 5 null terminators:
  constexpr int len = 15;
  char buf[len]{};                            // braces to initialize with null terminators
  for (int i = 0; i < 10; ++i) buf[i] = '?';  // overwrite with 10 '?'
  std::println("buf: {:?} (size: {})", buf, std::size(buf));

  // create a span stream to the static char buffer:
  // - pass len-1 to keep last null terminator alive
  std::ospanstream ospStrm{{buf, len-1}};

  // skip 2 characters:
  ospStrm.seekp(2, std::ios::cur);

  // write doubles as long as the span stream is valid:
  for (int i = 0; ospStrm; ++i) {
    // print current content of buf and the span stream:
    std::println("buf: {}", buf);
    std::println("     {}", ospStrm.span());

    // write the next value:
    ospStrm << ' ' << i * 1.1;
  }
}