Trouble with 2d array in program.
Hi there,
I'm working on a homework assignment and I am utterly stuck. I'm not quite sure where the problem in my program lies and was hoping someone could point me in the right direction.
The assignment is relatively simple; find groups of X's in a text file (in this program "group.txt")and output the number of groupings.
Here's the basic design:
1. Declare a 2d char array
2. Clear the array out (i.e. set all char to spaces).
3. Read in the array to the file (in this case "group.txt").
5. Call a recursive function to find the X groupings.
(The program should find 6 groupings. My program finds 20).
arraysize_row and arraysize_col are set in the assingnment; I can't change them. There are actually only 20 rows and 70 columns needed but the extra 2 rows and columns act as a border around the array so my program doesn't try to access things outside the array.
For some reason my groupings are being miscounted. I'm not sure if I'm reading the array incorrectly or if it is a problem somewhere else.
I've posted some of my code (only a portion of my recursive program).
Code:
#include <iostream>
#include <fstream>
using namespace std;
const int arraysize_row=22;
const int arraysize_col=72;
void displaythearray(char ma[][arraysize_col]);
void cleararray(char ma[][arraysize_col], int , int);
void readinfile(char ma[][arraysize_col]);
void groupfinder(char ma[][arraysize_col]);
void getgroup(char ma[][arraysize_col],int r, int c);
int main (void)
{
char matrix[arraysize_row][arraysize_col];
checkfile();
cleararray(matrix, arraysize_row, arraysize_col);
readinfile(matrix);
displaythearray(matrix);
groupfinder(matrix);
system("pause");
return 0;
}
void cleararray(char matrix[][arraysize_col], int r, int c)
{
int row=0, col=0;
for (row=0; row <r; row++)
for (col=0; col <c; col++)
matrix[row][col]=' ';
}
void readinfile(char ma[arraysize_row][arraysize_col])
{
ifstream infile;
infile.open("group.txt");
char mychar=' ';
infile.get(mychar);
for (int r=1; r<arraysize_row-1;r++){
for (int c=1; c<arraysize_col-1; c++){
ma[r][c]=mychar;
infile.get(mychar);
}
}
infile.close();
}
void groupfinder(char ma[][arraysize_col])
{
int group=0;
for (int row=1; row<(arraysize_row-1); row++)
{
for (int col=1; col< (arraysize_col-1); col++)
{
if (ma[row][col]=='X')
{
getgroup(ma, row, col);
group++;
}
}
}
cout<<"Number of groups: " <<group<<endl;
}
void getgroup(char ma[][arraysize_col], int r, int c)
{
ma[r][c]=' '; //set current location to space.
if (ma[r-1][c-1]=='X' ) // upper left of x
{
getgroup(ma,r-1,c-1);
}
//this goes on to test other locations near X.
// ...
else
return;
}
Any help is appreciated!