Align Cout Format as Table's Columns

Align cout format as table's columns

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;
}

Output aligned columns

In the class employee of print employee method:
Use this line to print.

cout << setw(20) << left << surname << setw(10) << left << empNumber << setw(4) << hourlyRate << endl;

You forgot to add "<< left". This is required if you want left aligned.

Hope it ll useful.

C++ and table format printing

You can use the std::setw manipulator for cout.

There's also a std::setfill to specify the filler, but it defaults to spaces.

If you want to center the values, you'll have to do a bit of calculations. I'd suggest right aligning the values because they are numbers (and it's easier).

cout << '|' << setw(10) << value << '|' setw(10) << value2 << '|' << endl;

Don't forget to include <iomanip>.

It wouldn't be much trouble to wrap this into a general table formatter function, but I'll leave that as an exercise for the reader :)



Related Topics



Leave a reply



Submit