读取2d数组并显示它(c++)
Reading in a 2d array and displaying it (c++)
所以我的代码的前提是从。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文件::
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
您忘记在txt中读取新行符号。如果你查看gameBoard数组,你会发现第二行的第一项是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
}
相关文章:
- 比较并显示使用最小值(a,b)和最大值(a、b)升序排列的4个数字
- C++,OpenCV,尝试显示图像时"OpenCV(4.3.0) Error: Assertion failed (size.width>0 && size.height>0)"此错误
- 字符串-C++后显示的随机字符
- 继承期间显示未知行为的子类
- 仅使用绝对值对数组进行排序,并在C++中显示实际值
- 程序崩溃并显示"std::out_of_range"错误
- 如何在C++中用std::cout正确显示带十六进制的字符串文本
- 为什么在C的循环中使用printf的Rust代码不显示输出,而在C++的循环中显示std::cout
- 从数据库实时显示QT c++中的数据
- 当使用比格式支持的精度更高的精度来显示数字时,会写出什么数据
- 显示错误输出的简单数组排序程序
- Qt自定义QPush按钮未显示在布局上
- C++射线示踪剂ppm表示没有足够的数据来显示图像
- 显示基于用户输入的整数的字符
- 使用QTreeView,如何通过调用函数只突出显示特定的行/列
- 应用程序崩溃并显示"symbol _ZdlPvm, version Qt_5 not defined in file libQt5Core.so.5 with link time reference"
- 示例外壳应用程序显示的 V8 "segmentation fault (core dumped)"错误
- 如何使 windows 命令提示符在C++可执行文件上显示返回值?
- 密码登录程序将永远循环并显示不正确的结果
- std::strftime 在 Windows 中使用 GMTIME 将时区 UTC 显示为 UTC+1