views:

1010

answers:

3
+6  Q: 

cout Formatting

Hi, 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
+5  A: 

I advise using Boost Format. Use something like this:

cout << format("%|1$30| %2%") % var1 % var2;
Leon Timmermans
Any other ideas, except Boost?
BobS
+9  A: 

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;
}
eed3si9n
Does not give me what I want.. are you sure this is correct?
BobS
You forgot to add "<< left". This is required if you want left-aligned fixed fields.
Raymond Martineau
Beaten by Raymond by 15 seconds!
eed3si9n
std::left is not reset on every formatted output, you only need it once. (The stream's width *is* reset.)
Roger Pate
+1  A: 

You must find the length of the longest string in the first column. Then you need to output each string in the first column in a field with the length being that of that longest string. This necessarily means you can't write anything until you've read each and every string.

Isn't there a easier way? Using setw or something.
BobS
>Isn't there a easier way?Not unless you can predict the future.>Using setw or something.Yes, setw is one way to "output each string in the first column in a field with the length being that of that longest string."
Most formatted output I've seen doesn't bother to find the max size of a field and if it overruns a decent value, oh well, but the formatting looks a little weird when it does.
Greg Rogers