打印数组内容时出现奇怪的值
Weird values when printing contents of array
当打印出2D数组的内容时,我得到了一些奇怪的值。
行和列的内容由用户设置。在这种情况下,两者都是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个问题。首先,您的数组未初始化,您希望它在其中有空格。因此,在开始设置边界之前,请先填充空格。
第二,你用来填充边界的循环每个都有两个短元素,例如
for(int a=0; a<rows; a++)
应为:
for(int a=0; a<rows+2; a++)
相关文章:
- 动态分配的聊天数组打印缺失的数据和空
- 对象数组打印空白字符串
- 数组打印"random"值时出现问题
- 数组打印出垃圾值
- 数组打印奇怪的字符,例如 ∟ @
- 测量我的随机数数组打印的时间始终显示为 0 秒
- 数组打印出错误的数字
- 从对象数组打印字符串对象
- 您好,如何防止此函数使用质数数组打印 1
- 如何从主内部的数组打印总计
- 如何将数组打印为矢量形式
- 有人能给我一些关于在C++中使用数组打印出丰富、完美和不足的数字的提示吗
- 为什么我的C++数组打印相同的值
- 如何阻止我的数组打印地址
- 将值输入到结构数组 + 打印输出
- C++11 为什么 cout 从布尔数组打印大整数
- 从字符串数组打印其中一个字符串时出现空指针赋值错误
- 将无符号字符数组打印为十六进制
- 缩短的数组打印错误的结果
- C++中的字符串数组:打印额外的字符