CgtyKy CgtyKy - 1 month ago 10
C++ Question

Reading from file and writing to 2D vector

When i tried to print my 2D vector, it's only read 3rd line (which is first line of maze) and ignore rest of maze. My maze is something like that;

11
11
X XXXXXXXXX
X X 1 X
X XXXXX X X
X X X 1
XXXXX XXX X
X X X X
X X XXX X X
X X X X
X XXXXXXX X
X X
XXXXXXXXXXX


but my end result is just repating first line like that;

11
11
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX
X XXXXXXXXX


Clearly I am mistaking something in my while loop...

#include <iostream>
#include <stdio.h>
#include "Maze.h"
#include "hw2.cpp"

void PrintVec2D(vector< vector< char> > &v)
{
for (size_t i=0; i<v.size(); i++)
{
for(size_t j=0; j<v[i].size(); j++)
cout << v[i][j];

cout << '\n';
}
}

void PrintVec1D(vector<char> &v)
{
for (size_t i=0; i<v.size(); i++)
cout<< v[i];
}

int main(int argc, char *argv[]){

string line;
ifstream myfile (argv[1]);

if (myfile.is_open())
{
//read just first two lines for rows and cols
string firstline;
getline(myfile, firstline);
int rows = std::stoi(firstline);

string secondline;
getline(myfile, secondline);
int cols=std::stoi(secondline);

//create 2d vector
vector< vector<char> > _maze;

//read rest of the file for maze structure
//I think my problem is in this while loop...
string line2;
int ra = 0;
int rb = 0;

while(ra<cols)
{
getline(myfile, line2);
vector<char> newRow(line2.begin(),line2.end());

while (rb<rows)
{
_maze.push_back(newRow);
ra++;
rb++;
}
}

PrintVec2D(_maze);
myfile.close();
}

else cerr << "Unable to open file";
return 0;
}

Answer

Your loop should look like this:

for(size_t ra = 0; ra < cols; ++ra)
{
    std::string line;

    if(std::getline(myfile, line))
    {
        vector<char> newRow(line.begin(), line.end());
        _maze.push_back(newRow);
        // or just _maze.emplace_back(line.begin(), line.end());
    }
}

I couldn't find the use for the second loop and rb variable. Since newRow is already an array, what's the point in adding it for each row?