1

enter image description here

I've got an assignment, shortly described, i've got to make an simple battle naval game. I thought it would be easy but i'm stuck. But right now i'm stuck. I've got one problem, i can't properly show my array, it does't align well. It would be great if you could help me

void show(char BATTLEFIELD[columns][rows])
{
    std::string alfa[rows + 1] = { "A|", "B|", "C|", "D|", "E|", "F|", "G|", "H|", "I|", "J|" };

    char num[11] = { ' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9' };

    for (int i = 0; i < 11; i++)
    {
        std::cout << std::setw(width) << num[i];
    }

    std::cout << std::endl;
    for (int z = 0; z < (columns*width); z++)
    {
        std::cout << "-";
    }
    std::cout << std::endl;
    for (int i = 0; i < columns; i++)
    {

        for (int z = 0; z < rows; z++)
        {
            if (z == 0)
            {
                std::cout << alfa[i];
            }
            std::cout << std::setw(width) << veld[i][z];
        }
        std::cout << std::endl;
    }
    std::cout << std::endl;
}

I'll put two pictures with the expected and unexpected result.

Expected result:

Expected result

Unexpected result:

Unexpected result

Scheff's Cat
  • 19,528
  • 6
  • 28
  • 56
  • Hi. What were you expecting to see and what is actually showing? – Spencer Dec 27 '19 at 00:38
  • Hey, thanks for tip, i've put two pictures of the (un)expexted results. – Empress_Azula Dec 27 '19 at 01:02
  • 1
    In other words, your problem is aligning the column numbers and the line of dashes underneath it? Just cout an extra space or two before you generate the line? (The game is usually called [Battleships](https://en.wikipedia.org/wiki/Battleship_(game)).) You can also generate the column and row headings: you don't need to store them as strings. – Rup Dec 27 '19 at 01:13
  • Are you trying to print "Waag uw kans:" at the bottom of the column? If so, create an array of char and assign each character to each row at the last column. – Harrison Chong Dec 27 '19 at 08:20

1 Answers1

0

Assuming those declarations

constexpr int rows{10};
constexpr int columns{10};
constexpr int width{3};

The visual discrepancies between the results are due to a couple of issues.

The horizontal line made of '-' is one width short (you are calculating the size of the table, but you missed the labels). You could take advantage of a std::string constructor to print it

std::cout << '\n' << std::string((columns + 1) * width, '-') << '\n';

To allign the other rows, you just need an extra space.

std::cout << ' ' << alfa[i];
//           ^^^                                  You could use std::setw(width), instead
for (int z = 0; z < rows; z++)
{
     std::cout << std::setw(width) << veld[i][z];
     //                               ^^^^        Note that the parameter is called BATTLEFIELD 
}
std::cout << std::endl;
Bob__
  • 12,361
  • 3
  • 28
  • 42