0

My goal is to have 3 columns of integers aligned like so:

3       109     136     223
4       95      237     230
5       200     76      153

With my code, this is the output I'm getting though:

enter image description here

I use a for loop to iterate through a vector and print the numbers.

Here is my for-loop which prints these numbers:

for (int i = 0; i < v.size(); i++)
  {
    cout << (i + 1);
    cout.setf(ios::left);

    cout.width(6);
    cout << " " << v[i].firstColumn;

    cout.width(8);
    cout << " " << v[i].secondColumn;

    cout.unsetf(ios::left);
    cout << endl;
  }

How can I make it so all of integers line up nicely? It seems as though the higher digit numbers are offsetting the columns (IE going from 9 to 10). Is there a way to fix this?

genpfault
  • 51,148
  • 11
  • 85
  • 139
Norse
  • 5,674
  • 16
  • 50
  • 86
  • 4
    Things are going wrong in the first column because you didn't set a width. Try this `cout.width(2); cout << (i + 1);` – john Jun 28 '19 at 21:22
  • You'll save yourself a lot of angst if you get your hands on the `fmt` libraries. The fact that they're being scheduled for inclusion in the standard means they'll be available to all and they do a much better job of output formatting than `iostream`. – paxdiablo Jun 28 '19 at 21:50
  • Possible duplicate of [C++ how to right justify multiple pieces of data](https://stackoverflow.com/questions/40706786/c-how-to-right-justify-multiple-pieces-of-data) – zett42 Jun 28 '19 at 21:59
  • 3
    Make sure to call `width()` *immediately* before the output of the numbers, it will be reset to zero after each output operation. You are actually setting width only for output of `" "`. – zett42 Jun 28 '19 at 22:01

1 Answers1

0

Your code does not match your goal. But in general, you need to set a width for each of the columns, including for the column that holds the i + 1 value, eg:

for (int i = 0; i < v.size(); i++)
{
    fmtflags oldflags = cout.setf(ios::left);
    cout << std::setw(8) << i + 1;
    cout << std::setw(8) << v[i].firstColumn;
    cout << set::setw(8) << v[i].secondColumn;
    ...
    cout.flags(oldflags);
    cout << endl;
}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770