我有一个二维数组。有一个角色U
。我的代码搜索字符然后输出数组,但只显示U
及其周围的每个字符。某处我的代码出错了,U
似乎输出正好相反的位置。
原始数组为gameboard[]
,可以正常读取。我们也不能使用向量,指针,只是我已经使用过的
int boardSizeRow;
int boardSizeCol;
inputFile.open("C:\\Users\\Michael\\Desktop\\fileboard1.txt");
inputFile >> boardSizeRow;
inputFile >> boardSizeCol;
inputFile.get();
char gameBoard[21][21];
for (int row = 0; row <= boardSizeRow; row++)
{
for (int col = 0; col <= boardSizeCol; col++)
{
gameBoard[row][col] = inputFile.get();
}
//inputFile.get();
}
for (int row = 0; row <= boardSizeRow; row++)
{
for (int col = 0; col <= boardSizeCol; col++)
{
cout << gameBoard[row][col];
}
//cout << endl;
}
bool toPrint[21][21] = {false};
for (int i = 0; i < boardSizeRow; i++ )
{
for (int j = 0; j < boardSizeCol; j++)
{
if (gameBoard[i][j] == 'U')
{
toPrint[i][j] = true;
toPrint[i][j-1] = true; //West
toPrint[i][j+1] = true; //East
toPrint[i-1][j] = true; //North
toPrint[i+1][j] = true; //South
}
}
}
for (int i = 0; i < boardSizeRow; i++ )
{
for (int j = 0; j < boardSizeCol; j++)
{
if (toPrint[i][j] == true)
{
cout << gameBoard[i][j];
}
else
{
cout << "0";
}
}
cout<<endl;
}
原始数组:
WWWWWWWWWW
W WW GO W
W WW WWW W
W W GW
WPWG WW W
WWWDWK WW
W GW W W
W WW KWAW
W SW UW
WWWWWWWWWW
**通缉输出:
0000000000
0000000000
0000000000
0000000000
0000000000
0000000000
00000000A0
00000000UW
00000000W0
这是一个随机输出的示例:http://tinypic.com/r/2ujo8/6
答案 0 :(得分:0)
尝试这样的事情
for (int i = 0; i < boardSizeRow; i++ )
{
for (int j = 0; j < boardSizeCol; j++)
{
if (gameBoard[i][j] == 'U')
{
toPrint[i][j] = true;
if(j!=0)
toPrint[i][j-1] = true; //West
if(j!=(boardSizeCol-1))
toPrint[i][j+1] = true; //East
if(i!=0)
toPrint[i-1][j] = true; //North
if(i!=(boardSizeRow -1))
toPrint[i+1][j] = true; //South
}
}
}
答案 1 :(得分:-1)
考虑切换行和列进行打印?
for (int j = 0; j < boardSizeCol; j++)
{
for (int i = 0; i < boardSizeRow; i++ )
{
if (toPrint[i][j] == true)
{
cout << gameBoard[i][j];
}
else
{
cout << "0";
}
}
cout<<endl;
}