Bugs
You say:
I am trying to print a board exactly like this with the multidimensional array.
But, in reality, you are not... you only print the first item from the 2D array, and the rest of the board is printed from the constant string values. See this article describing C++ array initialization
char score[10][10] = {' '};
The above code only initializes the first position of the score 2D array, and the remaining cells in the array are left as null-characters.
When those null-characters are printed in the j loop
:
for (int j = 0; j < 10; j++) {
cout << score[i][j];
}
The all do nothing (except the very first cell at score[0][0]
) because they become zero-length strings.
Thus, only the first line, and the first value get printed. To compensate for this, you are printing an constant-string value to complete the line, but, the first line is one character longer (because you printed score[0][0]
) than the others, so the first line has to have a single-char shorter constant to complete it, and you need the if(i == 0){...
condition.
I have made this obvious by initializing the array with an x
(char score[10][10] = {'x'};
) in this ideone which produces:
a b c d e f g h i j
+-------------------+
0|x |
1| |
2| |
3| |
4| |
5| |
6| |
7| |
8| |
9| |
+-------------------+
You need to correctly initialize the array....
char score[10][10] = {};
for (int i = 0; i < 10; i ++) {
for (int j = 0; j < 10; j++) {
score[i][j] = ' ';
}
}
Other
you are using the grid-size 10 as a magic number in a lot of places. You should probably make it a constant.....
Alternative.
C++ is not my primary language, and this is hardly a good example of a C++ program, but I have re-written your program as.... available on ideone as well ... This is the code that you should really be reviewed on ....
#include <iostream>
using namespace std;
#include <vector>
#include <string.h>
int main(){
char score[10][10] = {};
for (int i = 0; i < 10; i ++) {
for (int j = 0; j < 10; j++) {
score[i][j] = 'x';
}
}
cout<< " a b c d e f g h i j"<< endl;
cout <<" +-------------------+"<< endl;
for (int i = 0; i < 10; i++) {
// print the first character as part of the opener.
cout << " " << i << "|" << score[i][0];
for (int j = 1; j < 10; j++) {
// only add spaces for subsequent characters.
cout << " " << score[i][j];
}
cout << "|" << endl;
}
cout <<" +-------------------+"<< endl;
}
because the above code initializes the 2D array with x
, it prints the following grid:
a b c d e f g h i j
+-------------------+
0|x x x x x x x x x x|
1|x x x x x x x x x x|
2|x x x x x x x x x x|
3|x x x x x x x x x x|
4|x x x x x x x x x x|
5|x x x x x x x x x x|
6|x x x x x x x x x x|
7|x x x x x x x x x x|
8|x x x x x x x x x x|
9|x x x x x x x x x x|
+-------------------+
j
loop, and also print all the blanks in theif(i == 0){..} else {...}
blocks. i.e. why are you outputting fromscore
in thej
loop at all? \$\endgroup\$