Search code examples
c++ifstream

Displaying a Game-board from a txt file by reading in each char


I am trying to display

X  XXXXXXX  XXXXX   XXXXXXXXXXXXX   XXXX
X XXXXXXXX   XXXXXXXXXXXXXXXXXXXXX   XXX
XXXXXXXXXXXXXXXXXXXXX      XXXXXXXXXXXXX
XXXF        -----      XX           XXXX
XXXXXXXXXX  XXXXXX  XXXXX          FXXXX
XXXXXXXXXX  XXXXXX  XXX XXXX  XXXX--XXXX
XXXXXXXX    XXXXXX  XXXXXXXX   XXX--XXXX
XXXXXXX  XXXXXXX    XXXXXXXXX       XXXX
XXXXXX  XXXXXXXX  XXXXX XXXXX     --XXXX
       XXX   XXX  XX XX XXXXXXXXXX--XXXX
       XXX  XXXX  XXXXXXXXXXXXXXXX--XXXX
XXXXXXXXXX XXXXX  XX-          XXX--XXXX
XXX  XXXXXXXXXXX  XX----XXXX      --XXXX
XXXX XXXXXF           XXXXXX     XX$XXXX
XXXXXXXXXXX          XXXXXXXXXXXXXXXXXXX

I am using, Where ROWS = 15 and COLS = 40

for (int row = 0; row < ROWS; row++)
{
       for (int col = 0; col < COLS; col++)
       {
            board[row][col] = inFile.get();
            cout << board[row][col];
       }
}

It is essential that this table is stored in the character array. Though when I display the table the final row doesn't display fully.

Why isn't the table coming out correctly?


Solution

  • You're probably trying to store the newline characters in the board array. You need to add an additional .get() after every inner loop to grab the newline so it won't get pulled into your array:

    for (int row = 0; row < ROWS; row++)
    {
         for (int col = 0; col < COLS; col++)
         {
              board[row][col] = inFile.get();
              cout << board[row][col];
         }
         // Pull out the newline
         inFile.get();
         cout << std::endl;
    }