0

我有一个二维数组。里面有一个字符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

4

2 回答 2

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  

       }
   }
}
于 2013-04-12T12:41:31.213 回答
-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;
 }
于 2013-04-12T12:57:17.117 回答