Reputation: 143
I am making a minesweeper type program for my c++ class where I read a file like this
4 4
*...
....
.*..
....
3 5
**...
.....
.*...
0 0
and then output a file like this
Field #1:
*100
2210
1*10
1110
Field #2:
**100
33200
1*100
I figured I'd start out by reading the contents of the grid in the input file into a 2-d character array, except I would replace the periods with zeros. Then hopefully later I could do some math on the character array (not sure if that works well. I'm new to c++).
Anyways, I'm trying to check whether a character is an asterisk but that condition always returns false even if the character is an asterisk. What am I doing wrong?
#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";
}
}
Upvotes: 2
Views: 169
Reputation: 158469
You are using Grid
unitialized here:
if (Grid[iRows][iCols] == '*')
this needs to be moved before the if check:
mineData >> Grid[iRows][iCols];
and then you can just check if it is not an *
and set it to 0
.
Upvotes: 1
Reputation: 8805
Your Grid
is empty. You have initialized Grid
but have not read any data into it, so checking whether there will be an asterisk in Grid
will definitely return false
.
Instead of:
if (Grid[iRows][iCols] == '*') //Empty array will return false
Do this:
char tmp;
if (mineData >> tmp == '*')...
Upvotes: 1