Search code examples
c++vectorfstreamifstream

Read in a file for word search game C++


I am attempting read in a file and create a 2D vector to store the game board for a word search game but I can't seem to get it to read more than the first line. I'm sure it is something small but I put in a test display for the 'board' vector and all that shows up is the first line of the text file.

Here is some of my code:

'Board.cpp'

#include "stdafx.h"
#include "Board.h"
#include <fstream>
#include <iostream>
using namespace std;


Board::Board(void)
: rows(0)
{
}


Board::~Board(void)
{
}

void Board::readInFile(void)
{
    ifstream indata;
    indata.open("Puzzle.txt");
    indata >> rows;
    for(int i = 0; i < rows; i++){
        char tmpChar;
        for(int j = 0; j < rows; j++){
            indata >> tmpChar;
            row.push_back(tmpChar);
        }
        board.push_back(row);
    }
    indata.close();
}

'Board.h'

#pragma once
#include <vector>
using namespace std;
class Board
{
public:
    Board(void);
    ~Board(void);
    void readInFile(void);
protected:
    vector<vector<char>> board;
    vector<char>row;    
protected:
    int rows;
};

Here is how the text file is set up:

16

BDXWASEESPHWEBGB

SIGJVAWDFLCTZIAM

ENKVESMARNAEBRRI

IKOEOPZLUKMVJDDL

KLIRELOBSNPOFWEC

SBOHKLLRHSIFPANA

RSKWMEEEPEITPTPE

EZPIELLLYMOOQCDH

TAWDLGGLZBUNDHOJ

ASIOJNFOPKAJAPBP

WLRCIILROZXLSCID

SKATEBOARDGCLCIA

LLABESABIVOTNVVE

VOFRISBEETMIEVZG

BWADEVAUCYCSWING

XNJFJPZHBTBFTSAW


Solution

  • There are much better ways to handle input files. Firstly, rather than using a vector<char>, just use a std::string, and rather than using a vector<vector<char> >, just use a vector<string>. I'm not sure I understand why row is a member of the class if it is only being used to fill the board. Anytime you need the last item in board you can just do board.back() or *board.rbegin().

    void Board::readInFile(void)
    {
        ifstream indata("Puzzle.txt", ios::in);
        if(!ifstream.is_open())
            return;
        indata >> rows;    //you don't really need to do this if you take 
                             //the row count out of the file, but if you can't 
                             //change the file, leave it in so as not to corrupt 
                             //the loop that follows
        string line;
        while(getline(indata, line)){
            board.push_back(line);
        }
        indata.close();
    }
    

    Really, you don't need to have the file store the rows variable.


    Your function would also be more reusable if readInFile took the filename as a parameter so it could open anything instead of only one specific filename.