初始化数组工作得很好,但是当试图将其打印出来时,它会打印出一个额外的列和一个意外字符
Initializing an array works fine, but when trying to print it back out it prints an extra column and an unexpected character
所以编译没有问题。我遇到的问题是,当它打印到控制台时,右下角有一个额外的列和一个奇怪的ascii字符。如果我试图减小数组的大小,我就不能再用9个元素来初始化它了——我必须有9个元素才能使它成为一个井字棋棋盘。我认为这是一个错误,但如果是这样,我不知道如何解决它。我读过不少类似的"井字游戏"问题,但他们似乎没有同样的问题。
#include <iostream>
using namespace std;
int main ()
{
int countrow, countcol, play=1, subscript1, subscript2;
int ARRAY_ROWS = 3, ARRAY_COLS =3;
char board [3][3] = {{42, 42,42}, {42, 42,42}, {42, 42,42}};
char input;
while(play>0)
{
for(countrow = 0; countrow<ARRAY_ROWS; countrow++)
{
for(countcol=0; countcol<ARRAY_COLS; countcol++)
{
cout<<board [countrow][countcol];
}
cout<<board[countrow][countcol];
cout<<endl;
}
cout<<"Player 1, enter your mark using a row column coordinate system.n";
cin>>subscript1>> subscript2;
subscript1+=1;
board[subscript1][subscript2] = 88;
cout<<"Player 2, enter your mark using a row column coordinate system.n";
cin>>subscript1>> subscript2;
board[subscript1][subscript2] = 79;
}
system("pause");
return 0;
}
问题是:
for(countrow = 0; countrow<ARRAY_ROWS; countrow++)
{
for(countcol=0; countcol<ARRAY_COLS; countcol++)
{
cout<<board [countrow][countcol];
}
cout<<board[countrow][countcol];
//^^^^^This one is redundant and you are accessing invalid memory block
//^^^^^^ countcol is out of bound
cout<<endl;
}
您有以下行的冗余副本:
cout<<board[countrow][countcol];
这将导致每行多出一列的垃圾数据(countcol = 3,超出数组的边界)。
在你的内循环之后,你有另一个
cout<<board[countrow][countcol];
你不需要…删除它,多余的列就没有了。
相关文章:
- 我在 C++ 中创建了一个函数来递归反转字符串,但是之后如何使功能打印一个 endl?
- 打印一个类似雷电的图案
- 打印一个带有静态 int 的函数,有一个 std::cout 和多个 std::cout 有什么区别?
- 打印一个变量将打印另一个变量的值(以 C++ 为单位)
- 在C 函数中打印一个来自LUA的静态变量
- 如何打印一个字符阵列和其中的特定字符
- 代码只打印一个倍数而不是 3
- C Cout如何打印一个char*
- C 打印一个分子和分母的小数
- 如何从最后打印一个双端
- 为什么一次打印一个字符比提前连接它们慢
- 如何在C 中打印一个对象的2D向量
- 如何仅从矢量打印一个元素
- 打印一个列表给出错误,指出迭代器不可递减
- 我的任务是在框架内打印一个字符串,例如一个正方形
- 如何使用std :: fprintf()打印一个长字符串
- 如何打印一个带有整数的字符串C
- 我如何打印一个元组矢量
- 在OpenGL中打印一个红色三角形
- C 如何用逗号(而不是点)在文件中打印一个双小数号