Search code examples
c++arraysfile-iocharifstream

Strange characters follow when ifstream reads characters into 2D array


I'm working on a problem which asks me to read a .txt file containing a word puzzle into a 2D-array of type char and output the words found. I'm having trouble reading in the puzzle. Here is the code I use now to read in the .txt file and print out the dimensions and the puzzle itself:

ifstream in("puzzle.txt");
string line;
if (in.fail())
{
    cout << "Failed to open puzzle." << endl;
    exit(1);
}

int nrows = 0;
int ncols = 0;
getline(in, line);
ncols = line.size();
++nrows;
while(getline(in, line))
    ++nrows;

in.close();
cout << nrows << ", " << (ncols+1)/2 << endl;

// putting puzzle into a vector of vectors(2D array)
char A[nrows][ncols];
int r = 0;
int c = 0;
char ch;
in.open("puzzle.txt");
while (in >> ch)
{
    A[r][c] = ch;
    if (++c >= ncols)
    {
        c = 0;
        ++r;
    }
}
A[r][c] = 0;

for (int r = 0; r < nrows; ++r)
{
    for (int c = 0; c < ncols; ++c)
        cout << A[r][c] << " ";
    cout << endl;
}

Right now with this code I have, it seems to have read in all the characters at first, but then strange characters follow.

The result looks like this with an 8x8 puzzle:

8, 8

r d z i t p m f t e k a n s t

d t i b b a r o o k e l a h w

a a c j i e p n d k s d e o e

m z i h z i y l a t x i s h h

e e l s J ≡ o ` : ≡ o α J ≡

o ¿ ■ ` V Ω o

   h ²

` α J ≡ o Ç

  ╢ 5 ╛ s ] 6 @   α J ≡ o

The puzzle ends with "e e l s". I did not want the rest.

Another problem is that besides having strange characters this puzzle also was not printed according to the current dimension, which is only 8 characters per line.

I have read about solutions involving inserting the null character, but I'm still not quite sure how to do so with a 2D-array of characters.

Thanks!


Solution

  • The ncols variable doesn't get the value you want it to have. Because the line.size() returns the complete size of the array including separator character. Therefore the double dimensional array is filled with wrong number of columns and some of the last lines are left with the initial random characters.