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:
11111
10001
10001
10001
11111
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} }
Any help is appreciated!
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];}