Search code examples
c++multidimensional-arrayfstreamifstream

How can I save data from an external file into a 2D array? (C++)


I'm making a simple console game in C++ and I would like to be able to read a map from a .txt file and save it as a 2D array. I believe something like this is possible using fstream.
I'm also not sure whether it is possible to create a 2D array's size based on how large the map is from the external file.

I am trying to get it to work a bit like this:


.txt file in which i'm taking map from:

11111
10001
10001
10001
11111


The actual 2D array:

char map[][] = { {1,1,1,1,1},
                 {1,0,0,0,1},
                 {1,0,0,0,1},
                 {1,0,0,0,1},
                 {1,1,1,1,1} }


I'm a bit of a newbie when it comes to C++ so I don't quite understand everything yet. This is one of my first times reading from an external file so don't expect much from me :)

Any help is appreciated!


Solution

  • Firstly, add the input file(e.g. input.in, input.txt) in your project. Initiate a new stream to read data from that file. Read the numbers row by row and put the numbers in the matrix.

    #include <fstream>
    using namespace std;
    
    ifstream f(“input.in”);//declare the stream
    
    int matrix[num_of_rows][num_of_columns];
    
    void read(){
    for(int i=0;i<num_of_rows;i++)
    for(int j=0;j<num_of_columns;j++)
    f>>matrix[i][j];}