Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Align cout format as table's columns

Tags:

c++

string

format

I'm pretty sure this is a simple question in regards to formatting but here's what I want to accomplish:

I want to output data onto the screen using cout. I want to output this in the form of a table format. What I mean by this is the columns and rows should be properly aligned. Example:

Test                 1 Test2                2 Iamlongverylongblah  2 Etc                  1 

I am only concerned with the individual line so my line to output now (not working) is

cout << var1 << "\t\t" << var2 << endl;

Which gives me something like:

Test                 1 Test2                  2 Iamlongverylongblah         2 Etc                  1 
like image 659
BobS Avatar asked Nov 09 '08 01:11

BobS


People also ask

How to Align print in C?

You can use printf("%*s", <width>, "a"); to print any text right aligned by variable no. of spaces.


2 Answers

setw.

#include <iostream> #include <iomanip> using namespace std;  int main () {   cout << setw(21) << left << "Test"    << 1 << endl;   cout << setw(21) << left << "Test2"   << 2 << endl;   cout << setw(21) << left << "Iamlongverylongblah"     << 2 << endl;   cout << setw(21) << left << "Etc"     << 1 << endl;   return 0; } 
like image 61
Eugene Yokota Avatar answered Oct 09 '22 07:10

Eugene Yokota


I advise using Boost Format. Use something like this:

cout << format("%|1$30| %2%") % var1 % var2; 
like image 24
Leon Timmermans Avatar answered Oct 09 '22 05:10

Leon Timmermans