I am trying to write table to stdout with numerical data. I would like to format so that numbers are aligned like:
1234 23
312 2314
12 123
I know that max length of the number is 6 chars, is there a smart way to know how many spaces needs to be output before number so it looks exactly like this?
For fun:
output:
For c, use "%6d" to specify printing, i.e.
For c++,
Don't forget to
#include <iomanip>
.Use of cout is strongly recommended over printf for type safety reasons. If I remember correctly, Boost has a type-safe replacement for printf, so you can use that instead of you require the format-string, args form.
printf
may be the quickest solution:Prints:
Something similar can be achieved with an arduous and verbose sequence of iostream commands; someone else will surely post such an answer should you prefer the "pure C++" taste of that.
Update: Actually, the iostreams version isn't that much more terrible. (As long as you don't want scientific float formatting or hex output, that is.) Here it goes: