12

How can I output data to the console in a table in C++? There's a question for this in C#, but I need it in C++.

This, except in C++: How To: Best way to draw table in console app (C#)

Community
  • 1
  • 1
JT White
  • 517
  • 4
  • 9
  • 21

4 Answers4

17

Here's a small sample of what iomanip has:

#include <iostream>
#include <iomanip>

int main(int argc, char** argv) {
    std::cout << std::setw(20) << std::right << "Hi there!" << std::endl;
    std::cout << std::setw(20) << std::right << "shorter" << std::endl;
    return 0;
}

There are other things you can do as well, like setting the precision of floating-point numbers, changing the character used as padding when using setw, outputting numbers in something other than base 10, and so forth.

http://cplusplus.com/reference/iostream/manipulators/

Dawson
  • 2,673
  • 1
  • 16
  • 18
9

I couldn't find something I liked, so I made one. Find it at https://github.com/haarcuba/text-table

Here's an exmaple of its output:

+------+------+----+
|      |Sex   | Age|
+------+------+----+
|Moses |male  |4556|
+------+------+----+
|Jesus |male  |2016|
+------+------+----+
|Debora|female|3001|
+------+------+----+
|Bob   |male  |  25|
+------+------+----+
8

Can't you do something very similar to the C# example of:

String.Format("|{0,5}|{1,5}|{2,5}|{3,5}|", arg0, arg1, arg2, arg3);

Like:

printf("|%5s|%5s|%5s|%5s|", arg0, arg1, arg2, arg3);

Here's a reference I used to make this: http://www.cplusplus.com/reference/clibrary/cstdio/printf/

Tim S.
  • 55,448
  • 7
  • 96
  • 122
  • 3
    For tabular output, C's printf beats C++ horrendous I/O hands down. – David Hammen Jul 20 '11 at 00:04
  • @Walter This is definitely the issue - you can just pad to fix an underflow, but to handle overflows, you need all the logic and policies to wrap 'sensibly'. (Backtrack from overflow to the nearest delimiter, fall back to un-delimited wrapping for the edge case, and *then* worry about per-line formatting.) It's a relatively simple problem on its own, but probably more work than it's worth if you're doing it for aesthetic polish on an unrelated project. – John P Oct 03 '17 at 10:18
0

Check the column value length and also keep the length of value in mind to format.

printf(" %-4s| %-10s| %-5s|\n", "ID", "NAME", "AGE");

See how MySQL shell interface was designed, it will give you a good idea.

Vijay Kumar Kanta
  • 1,111
  • 1
  • 15
  • 25