Table layout using std::cout

15,444

Solution 1

Include the standard header <iomanip> and go crazy. Specifically, the setw manipulator sets the output width. setfill sets the filling character.

Solution 2

std::cout << std::setiosflags(std::ios::fixed)
          << std::setprecision(3)
          << std::setw(18)
          << std::left
          << 12345.123;

Solution 3

You may also consider more friendly functionality provided by one of these:

  • Boost.Format (powerful, but very heavy, more time and memory allocations than other mentioned)
  • Loki.SafeFormat
  • FastFormat (relatively new, but blazing fast library, also type-safe unlike the others)

Writing from memory, but should be something along these lines:

// Dumb streams:
printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);

// For IOStreams you've got example in the other answers

// Boost Format supports various flavours of formatting, for example:
std::cout << boost::format("%-14.3f%-14.3f\n") % a % b;
std::cout << boost::format("%1$-14.3f%2$-14.3f\n") % a % b;
// To gain somewhat on the performance you can store the formatters:
const boost::format foo("%1$-14.3f%2$-14.3f\n");
std::cout << boost::format(foo) % a % b;

// For the Loki::Printf it's also similar:
Loki::Printf("%-14.3f%-14.3f\n")(a)(b);

// And finally FastFormat.Format (don't know the syntax for decimal places)
fastformat::fmtln(std::cout, "{0,14,,<}{1,14,,>}", a, b);

Also, if you plan to stick with any of these formatting libraries, examine thoroughly their limitations in context of expressibility, portability (and other library dependency), efficiency, support of internationalisation, type-safety, etc.

Solution 4

You want to use stream manipulators:

http://www.deitel.com/articles/cplusplus_tutorials/20060218/index.html

Share:
15,444
Samda
Author by

Samda

Updated on June 04, 2022

Comments

  • Samda
    Samda almost 2 years

    How do I format my output in C++ streams to print fixed width left-aligned tables? Something like

    printf("%-14.3f%-14.3f\n", 12345.12345, 12345.12345);
    

    poducing

    12345.123     12345.123
    
  • Anonymous
    Anonymous about 15 years
    Links now, examples tomorrow afternoon (GMT time)
  • R. Martinho Fernandes
    R. Martinho Fernandes over 10 years
    Don't forget std::left for the left-alignment.
  • Iharob Al Asimi
    Iharob Al Asimi almost 9 years
    Is there a good reason why printf() wouldn't be a good choice?
  • Konrad Rudolph
    Konrad Rudolph almost 9 years
    @iharob The OP didn't ask for printf. That said, printf is a bad choice in C++ because it only handles builtin types, not user-defined types. It's also not type safe and allows potentially security relevant bugs to go undetected.