打印二维数组的内容时,我得到了一些奇怪的值。
行和列的内容由用户设置。在这种情况下,两者都是 4。
下面是我的代码,其中创建了板并使用 * 分配了边框轮廓,并且行和列有额外的 2 个边框元素。
int rows;
int columns;
while(!(file.eof()){
file >> rows >> columns;
}
char board [rows+2][columns+2];
//Set the top row border
for(int a=0; a<columns; a++){
board[0][a]='*';
}
//Set the left border
for(int a=0; a<rows; a++){
board[a][0]='*';
}
//Set the right border
for(int a=0; a<rows; a++){
board[a][columns+1]='*';
}
//Set the bottom border
for(int a=0; a<columns; a++){
board[rows+1][a]='*';
}
for(int z=0; z<rows+2; z++){
for(int x=0; x<columns+2; x++){
cout << board[z][x];
}
cout << endl;
}
for(int z=0; z<rows+2; z++){
for(int x=0; x<columns+2; x++){
cout << "[" << z << "][" << x << "]: " << board[z][x] <<endl;
}
}
这是输出:
****?*
*`
?*
**
**
****Qk
[0][0]: *
[0][1]: *
[0][2]: *
[0][3]: *
[0][4]: ?
[0][5]: *
[1][0]: *
[1][1]:
[1][2]: `
[1][3]:
[1][4]: ?
[1][5]: *
[2][0]: *
[2][1]:
[2][2]:
[2][3]:
[2][4]:
[2][5]: *
[3][0]: *
[3][1]:
[3][2]:
[3][3]:
[3][4]:
[3][5]: *
[4][0]:
[4][1]:
[4][2]:
[4][3]:
[4][4]:
[4][5]:
[5][0]: *
[5][1]: *
[5][2]: *
[5][3]: *
[5][4]: Q
[5][5]: k
当它应该打印时:
******
* *
* *
* *
* *
******
所以我不确定发生了什么,也不确定为什么每次程序运行时最后两个元素 [5][4] 和 [5][5] 似乎总是分配不同的字符。
最佳答案
2个问题。首先,您的数组未初始化,您希望它有空格。因此,在开始放置边框之前用空格填充它。
其次,您用于填充边界的循环每个都停止了 2 个元素,例如
for(int a=0; a<rows; a++)
应该是:
for(int a=0; a<rows+2; a++)
关于c++ - 打印数组内容时的奇怪值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9629278/