C++ 读取二维数组并显示它(c+;+;)

C++ 读取二维数组并显示它(c+;+;),c++,arrays,file-io,for-loop,multidimensional-array,C++,Arrays,File Io,For Loop,Multidimensional Array,因此,我的代码的前提是从.txt读取2d数组。阵列是一个游戏板,但前两条线决定了板的大小。在我读了之后,我想让它找到字符“U”所在的位置,然后显示数组,但只显示U及其周围的内容。问题是我不能让数组打印正确的大小,显示U的代码也不起作用 ifstream inputFile; int boardSizeRow; int boardSizeCol; inputFile.open("C:\\Users\\Michael\\Desktop\\fileboard2.txt"); inputFile >

因此,我的代码的前提是从.txt读取2d数组。阵列是一个游戏板,但前两条线决定了板的大小。在我读了之后,我想让它找到字符“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中的新行符号。如果您查看游戏板阵列,您会发现第二行的第一项是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
}
for(int行=0;行你能得到什么样的结果?你能编辑这个问题并将其添加到其中吗?那么我需要做什么更改?
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
}