-1

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!

  • Consider `std::ifstream`. It functions just like `cin` but for files. – Cruz Jean Apr 06 '19 at 02:14
  • Array sizes must be compile-time constants, so you have to use `std::vector`, ideally by wrapping it in some class to make a vector behave like a 2D map (a vector of vectors is very inefficient). For reading the file, I would recommend you to learn about file I/O from a [good book](https://stackoverflow.com/q/388242/9254539) since we don't teach broad topics like this from scratch here (nor do we write code for people). Instead, we like to help people with their existing attempts at solving a problem. – eesiraed Apr 06 '19 at 04:45
  • Thanks. I will have to have a good read. – Liam Boswell Apr 06 '19 at 06:53

1 Answers1

0

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];}