我正在为我的 C++ 类制作一个扫雷类型程序,我在其中读取这样的文件
4 4
*...
....
.*..
....
3 5
**...
.....
.*...
0 0
然后输出这样的文件
Field #1:
*100
2210
1*10
1110
Field #2:
**100
33200
1*100
我想我应该首先将输入文件中网格的内容读取到二维字符数组中,但我会用零替换句点。然后希望稍后我可以对字符数组进行一些数学运算(不确定这是否有效。我是 c++ 新手)。
无论如何,我试图检查一个字符是否是星号,但即使该字符是星号,该条件也总是返回 false。我做错了什么?
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
ifstream mineData;
mineData.open("input_mine_data.txt");
int numRows = 0;
int numColumns = 0;
mineData >> numRows;
mineData >> numColumns;
cout << numRows;
cout << numColumns;
cout << "\n\n";
char Grid[50][50];
for (int iRows = 0; iRows < numRows; iRows++)
{
for (int iCols = 0; iCols < numColumns; iCols++)
{
//if current character is an asterisk
if (Grid[iRows][iCols] == '*')
{
//put the asterisk in the Grid array
mineData >> Grid[iRows][iCols];
}
//if the current character is a period, put a zero
//in the grid array instead
else
{
Grid[iRows][iCols] = '0';
}
}
}
for (int iRows = 0; iRows < numRows; iRows++)
{
for (int iCols = 0; iCols < numColumns; iCols++)
{
cout << Grid[iRows][iCols];
}
cout << "\n";
}
}
最佳答案
您正在使用此处统一的Grid
:
if (Grid[iRows][iCols] == '*')
这需要在 if 检查之前移动:
mineData >> Grid[iRows][iCols];
然后您可以检查它是否不是 *
并将其设置为 0
。
关于c++ - 我在比较字符数组中的字符时遇到问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19507700/