Reputation: 107
I'm currently developing a simple naval battle game for my first exam at my college but i'm getting a strange output on my gameboard...
It should be iterating my "j" variable, but instead I get that strange character...
Here's my code:
//CREATES COORDENATES OF THE GAMEBOARD
//ATTRIBUTE ONE LETTER TO EACH TRAY LINE
for (i=0;i<11;i++){
tabuleiro[i][0] = letra[i-1];
}
//ATTRIBUTE ONE NUMBER TO EACH TRAY COLUMN
for (j=1;j<11;j++){
tabuleiro[0][j] = j;
}
//CREATES THE "SEA"
for (i=1;i<11;i++){
for (j=1;j<11;j++){
tabuleiro[i][j] = '~';
}
}
I've tryied to change my tabuleiro[0][j] = j;
to tabuleiro[0][j] = (j+'0');
but then it only iterates until 9 and give me strange characters again...
If I'm not wrong I think this has something to do with the ASCII code (please correct me if I'm wrong) but I've no clue how to fix this.
Could you explain me how can I solve this please.
Upvotes: 0
Views: 75
Reputation: 13533
The issue is the char code for 10 + '0' = 58
which is the char code for ':'. You might consider removing the column and row names out of the game array. They are just labels and not part of the game (I assume).
#define board_size 10
And
// Create game board and initialize grid to '~', in main() possibly
// Game is 10x10 grid
char tabuleiro[board_size][board_size];
for (int row = 0; row < board_size; row++) {
for (int col = 0; col < board_size; col++) {
tabuleiro[row][col] = '~';
}
}
Have a function that draws the game board:
void drawBoard(char tabuleiro[board_size][board_size]) {
// Print top line
printf(" ");
for (int col = 0; col < board_size; col++) {
printf(" %-2d", col+1);
}
printf("\n");
// Print grid
for (int row = 0; row < board_size; row++) {
// Print letter
printf("%c ", 'A' + row);
// Print board
for (int col = 0; col < board_size; col++) {
printf(" %c ", tabuleiro[row][col]);
}
printf("\n");
}
}
Upvotes: 3
Reputation: 50110
to have precise control of the character i suggest
tabuleiro[0][j] = "123456789T"[j];
This will pick the jth character from that string
BTW the reason you got ':' is becasue ':' is the next ascii character after '9' - see http://www.asciitable.com/
Upvotes: 4