初始化数组工作得很好,但是当试图将其打印出来时,它会打印出一个额外的列和一个意外字符

Initializing an array works fine, but when trying to print it back out it prints an extra column and an unexpected character

本文关键字:打印 一个 意外 字符 很好 工作 数组 初始化      更新时间:2023-10-16

所以编译没有问题。我遇到的问题是,当它打印到控制台时,右下角有一个额外的列和一个奇怪的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];

你不需要…删除它,多余的列就没有了。