Syrenthia
Syrenthia

Reputation: 144

How to read a labyrinth from a txt file and put it into 2D array

I just started a small project which reads a txt file like this:

4
XSXX
X  X
XX X
XXFX

So my question is how to read this and put the labyrinth to 2D char array in C++. I tried to use 'getline' but I just make my code more complex. Do you know if there is an easy way to solve this problem ?

char temp;
    string line;
    int counter = 0;
    bool isOpened=false;
    int size=0;

    ifstream input(inputFile);//can read any file any name
    // i will get it from user

    if(input.is_open()){

    if(!isOpened){
        getline(input, line);//iterater over every line
        size= atoi(line.c_str());//atoi: char to integer method.this is to generate the size of the matrix from the first line           
    }
    isOpened = true;
    char arr2[size][size];       

    while (getline(input, line))//while there are lines
    {
        for (int i = 0; i < size; i++)
        {

            arr2[counter][i]=line[i];//decides which character is declared

        }
        counter++;
    }

Upvotes: 3

Views: 1211

Answers (1)

Ziezi
Ziezi

Reputation: 6467

Your error is due to the fact that you are trying to declare an array with a size that is a non-constant expression.

In your case size representing the number of elements in the array, must be a constant expression, since arrays are blocks of static memory whose size must be determined at compile time, before the program runs.

To solve it you could either leave the array with empty brackets and the size will be automatically deduced by the number of elements you place in it or you could use std::string and std::vector and then to read the .txt file you could write something like:

// open the input file
ifstream input(inputFile);

// check if stream successfully attached
if (!input) cerr << "Can't open input file\n";

string line;
int size = 0;     

// read first line
getline(input, line);

stringstream ss(line);
ss >> size;

vector<string> labyrinth;

// reserve capacity
labyrinth.reserve(size);

// read file line by line 
for (size_t i = 0; i < size; ++i) {

    // read a line
    getline(input, line);

    // store in the vector
    labyrinth.push_back(line);
}

// check if every character is S or F

// traverse all the lines 
for (size_t i = 0; i < labyrinth.size(); ++i) {

    // traverse each character of every line
    for (size_t j = 0; j < labyrinth[i].size(); ++j) {

         // check if F or S
         if (labyrinth[i][j] == 'F' || labyrinth[i][j] == 'S') {

             // labyrinth[i][j]  is F or S
         }

         if (labyrinth[i][j] != 'F' || labyrinth[i][j] != 'S') {

             // at least one char is not F or S
         }
    }
}

As you can see this vector is already "a kind of" 2D char array only with a lot of additionally provided facilities that allow a lot of operations on its content.

Upvotes: 3

Related Questions