【问题标题】:Reading in a 2d array and displaying it (c++)读取二维数组并显示它(c++)
【发布时间】:2013-04-04 08:21:58
【问题描述】:

所以我的代码的前提是从 .txt 中读取二维数组。该数组是一个游戏板,但前两行决定了板的大小。在我读完它之后,我希望它找到字符“U”在哪里,然后显示数组,但只显示 U 和它周围的东西。问题是我无法让数组打印正确的大小,并且显示 U 的代码也不起作用。

ifstream inputFile;
int boardSizeRow;
int boardSizeCol;
inputFile.open("C:\\Users\\Michael\\Desktop\\fileboard2.txt");
inputFile >> boardSizeRow;
inputFile >> boardSizeCol;
inputFile.get();


char gameBoard[20][20];
for (int row = 0; row < boardSizeRow; row++)
{
    for (int col = 0; col < boardSizeCol; col++)
    {
        gameBoard[row][col] = inputFile.get();
    }
}


for (int row = 0; row < boardSizeRow; row++) //////////////TO TEST PRINT
{
    for (int col = 0; col < boardSizeCol; col++)
    {
        cout << gameBoard[row][col];
    }
}

cout << endl;
cout << endl;

const int ROWS = 20; 
const int COLS = 20;
bool toPrint[ROWS][COLS] = {false}; 
for (int i = 0; i < ROWS; i++ )
{
    for (int j = 0; j < COLS; j++)
    {
       if (gameBoard[i][j] == 'U')
       {
            //set parameters around:
            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 < ROWS; i++ )
{
    for (int j = 0; j < COLS; j++)
    {
       if (toPrint[i][j])
       {            
           cout << gameBoard[i][j] ;
       }
       else
       {
           cout <<"0";
       }
    }
    cout <<endl;
 }
cout << endl; 

return 0;

。 txt 文件::

20
20
WWWWWWWWWWWWWWWWWWWW
  W GO  W          W
W WW      w    S   W
W H W   GW  w      W
WPW  WW          G W
 WK       W        W
W W W  W    w   w  W
  WK WU            W
    SW      w  w   W
           W       W
    w    W       G W
  G    W       w   W
D   wwwww          W
         K   w  D  W
w w   W w   w      W
    ww  w    WWWWWWW
  G        w       W
    ww  w S    w   W
   WWW      G      W
WWWWWWWWWWWWWWWWWWWW

【问题讨论】:

  • 你得到什么输出?您可以编辑问题并将其添加到其中吗?

标签: c++ arrays file-io for-loop multidimensional-array


【解决方案1】:

您忘记读取 txt 中的换行符。如果你查看 gameBoard 数组,你会发现第 2 行的第一项是 10''。

修改代码:

for (int row = 0; row < boardSizeRow; row++)
{
    for (int col = 0; col < boardSizeCol; col++)
    {
        gameBoard[row][col] = inputFile.get();
    }
    inputFile.get();//read new line symbol here
}


for (int row = 0; row < boardSizeRow; row++) 
{
    for (int col = 0; col < boardSizeCol; col++)
    {
        cout << gameBoard[row][col];
    }
    cout<<endl;//output new line here
}

【讨论】:

  • 那我需要做些什么改变?
猜你喜欢
  • 2017-08-09
  • 1970-01-01
  • 2021-12-12
  • 1970-01-01
  • 2020-08-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多