format a string c++ code example

Example 1: C printf to string

// int sprintf(char *str, const char *format, ...);
char *printf_to_string()
{
  char buffer[128] = {0} //Must be big enough

  // writing printf output in buffer
  sprintf(buffer, "some %s here...\n", "text");
  // duplicate if needed
  return strdup(buffer);
}

Example 2: format string cpp

#include <iostream>
#include <format>
 
int main() {
    std::cout << std::format("Hello {}!\n", "world");
}

Example 3: c++ formatting

cout << setw(10) << "ten" << "four" << "four" << '\n';
// Display ten       fourfour

cout << setfill('-') << setw(80) << "-" << '\n';
// Displays 80 "-"

Tags:

Cpp Example