c++ - 我在比较字符数组中的字符时遇到问题

标签 c++ char

我正在为我的 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/

相关文章:

c++ - Win32 Windows 线程安全吗?

c++ - 包含 1 个指针的结构的大小

java - 创建输入字符菜单

c++ - 调试时出现 "myapp.exe has triggered a breakpoint"- 之后 Visual Studio 2015 Update 3 中的符号加载速度缓慢

c++ - 如何删除目录限定符以使用 Win32 API 简化路径名?

c++ - 如何在 C++ 中获取动态数组的大小

c - 如何让char为空?

c - 如何从 C 中的字符数组中获取字符串?

c# - 检测日文字符输入和 "Romajis"(ASCII)

c - 如何在 scanf 字符串中包含空格?