-1

Here's my code:

#include <iostream>
#include <iomanip>

using namespace std;

int main()
{
    int steve[2][3] = {{2, 3, 4}, {8, 9, 10}};

    //What the array will look like:
        // 2, 3, 4,
        // 8, 9, 10
    //They operate like coordinates: array[row number][index of element within row]

    //cout << steve[row][column];


    int n = 0;
    int i = 0;

    //my way
    while (n == 0 && i < 3)
    {
        cout << steve[n][i] << setw(2);
        i++;

        if (i == 3)
        {
            cout << endl;
            i = 0;
            n +=1;

            while (n == 1 && i<3)
            {

                cout << steve[n][i] << setw(2);
                i++;   
            }
        }
    }
}

My issue is my output looks like this:

2 3 4                                                                                                                      
 8 910

When I'm trying to get it to look like this:

2 3 4                                                                                                                      
8 9 10

Can someone please explain to me why setw() is not working, and what it is actually doing to my code? Just a head's up, I already tried simply using spaces on both output commands, like this:

cout << steve[n][i] << " "; 
cout << steve[i][n] << " ";

And it works the way I want it to, but I would really like to know how setw() works and why it is giving me this problem.

Thanks.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
SunGone
  • 29
  • 3
  • You do realise that `setw` works on the next item to be printed, not the previous? – john Apr 07 '20 at 10:00
  • When you do setw, it should be enough wide to be able to print the number inside. So if you setw to 2, then you will have _8_910. If you set to 3 you will have __8__9_10. Also it is right side aligned. But you want it to be left side aligned. – armagedescu Apr 07 '20 at 10:00
  • Add std::left for left alignment – armagedescu Apr 07 '20 at 10:01
  • Your last five numbers are being printed right aligned in a field of width 2. Since `10` is two digits you don't get a space before it. – john Apr 07 '20 at 10:02

1 Answers1

0

The output will be right hand side aligned, for the desired output you will need to align it to left hand side, width will still be two, but then you will have the blank space to the right and the value to the left:

8_9_10

instead of

_8_910

Using:

cout << left << setw(2) << steve[n][i];

As in the code, you use output formatting before the output.

If you were to have two contiguous values in the 10s you should use setw(3) otherwise you can't have spaces between them since those ocuppy both available spaces.

Live sample

On a side note, take a look at Why is "using namespace std;" considered bad practice?

Community
  • 1
  • 1
anastaciu
  • 23,467
  • 7
  • 28
  • 53