Home > Articles > Programming > C/C++

  • Print
  • + Share This
Like this article? We recommend

Like this article? We recommend

Lining Up Your Text

If you're trying to print a set of numbers to look like a table, you probably want your columns to line up nice and neat. The cout object includes a function called width that makes this easy. Here's a fourth take at our example:

cout << "Take 4" << endl;
cout.precision(3);
cout << showpoint;
cout.width(10);
cout << x << " ";
cout.width(10);
cout << y << " ";
cout.width(10);
cout << z << endl;
cout.width(10);
cout << p << " ";
cout.width(10);
cout << q << " ";
cout.width(10);
cout << r << endl;
cout << endl;

Yuck! You might not be too happy with the code at this point. Seems I just made a mess of the code. But bear with me, please. Here's the new output:

Take 4
    100     20     5
   3.14   0.333    1.00

Hey! That does look a little better! Notice how I did this formatting: Before writing each number, I called the width function, passing 10, which is the width of the printed column. As for any concerns about the code going off and turning ugly, don't worry: Remember that typically you won't be hard-coding a batch of numbers to print out. Instead, you'll be reading the numbers from somewhere else, such as from an array, and you'll have the code inside a loop. Thus, on each iteration of the loop, you simply call the width function and then write out your number. No biggie.

  • + Share This
  • 🔖 Save To Your Account