Reading data from a file into main

Hi,
I need help with reading a file given to us into the main.cpp using a 2D array.

The question is:
Implementing a function to read in a map from a file. The map is a 10 by 10 array of integers that is to be stored in a file: map.txt

the file map looks like this:
0 0
0 9 0 9 0 0 0 0 0 0
0 -1 0 0 0 0 0 9 0 0
9 -1 0 0 -1 9 -1 0 0 0
0 9 0 -1 0 0 0 -1 0 0
0 0 9 0 0 9 0 -1 0 0
0 9 -1 9 0 0 9 9 0 -1
9 0 0 0 -1 0 0 0 0 -1
0 -1 0 0 9 0 0 9 0 0
9 0 0 0 9 0 9 9 0 0
-1 0 9 0 9 0 9 0 0 999

The function must accept a 2D array as a parameter, then fill this 2D array using what is read in from the file.
If you read a 0, -1 or 999 then store it as a 0, -1 or 999 respectively in the array. However if a 9 is read in then we will generate a random number between 1 and 7 to store in the array instead. So for example if the following row is read in from the file: 0 0 -1 0 9 -1 0 9 0 0
Then it may be stored in the array like so:
0 0 -1 0 4 -1 0 2 0 0


Thanks guys

1
2
3
4
5
6
7
8
9
10
11
12
13
int array[10][10];

// read file into array
int* arrayLocationToWriteTo;
for (int eger=0; eger<100; eger++)
{
  inputFile >> *arrayLocationToWriteTo;
  if (*arrayLocationToWriteTo== 9)
  {
    *arrayLocationToWriteTo= randomNUmberBetweenOneAndSeven();
  }
  arrayLocationToWriteTo++;
}
Hi
thanks
so this is the way to do the question?
It's a way. It relies on you understanding what actually happens in memory when you create a 2D array.
So what happens in the memory when you create a 2D array
Nothing much,
int array[10][10];
100, continous blocks of memory are allocated for array(each block is of size of int), in case the 100 continuous blocks are not available it throws a memory alloc exceprtion.
If there isn't enough memory on the stack, that will likely cause your program to crash, but it won't throw an exception; and it's one contiguous block of memory with space for 100 elements.

@OP: If you don't attempt to solve this on your own, you're unlikely to get constructive responses. Show code.
Last edited on
You think this part's hard? Just wait until you get to the part where you have to encounter the monsters.
Topic archived. No new replies allowed.