savannaalexis
savannaalexis

Reputation: 65

Print a 2D Array from file in c++

I have a file Map.txt and there is a 2D array saved inside of that file, but whenever I try to print my 2D array in my main program I get crazy numbers. Code:

  cout << "Would you like to load an existing game? Enter Y or N: " << endl;
cin >> Choice;
if (Choice == 'Y' || Choice == 'y')
{
   fstream infile;
   infile.open("Map.txt");
   if (!infile)
       cout << "File open failure!" << endl;
   infile.close();
}
if (Choice == 'N' || Choice == 'n')
    InitMap(Map);

Map saved in file:

********************
********************
********************
********************
********************
********************
********************
**********S*********
*****************T**
********************

Output when program is run:

Would you like to load an existing game? Enter Y or N: 
y
88???????`Ė
?(?a????
??_?
?дa??g  @
 Z???@

        ?
 ?a??p`Ė??p]?
??_???`Ė?
??a??#E@??
??_??

Upvotes: 0

Views: 220

Answers (2)

Obaida.Opu
Obaida.Opu

Reputation: 464

This Code will show your Map.txt file in console. Don't forget to provide the exact path to open the file.

#include <stdio.h>

const int MAX_BUF = 100001;
char buf[MAX_BUF];

int main()
{
    FILE *fp = fopen("Map.txt","r"); //give the full file path here.
    while( fgets(buf,MAX_BUF,fp) )
    {
        puts(buf);
    }
    return 0;
}

Upvotes: 0

merlin2011
merlin2011

Reputation: 75565

I am going to hazard a guess that you want to read the file into a 2D character array. I will also assume for simplicity that you know how many rows and columns you need. The numbers below are for illustration only.

#define NUM_ROWS 10
#define NUM_COLS 20    

// First initialize the memory
char** LoadedMap = new char*[NUM_ROWS];
for (int i = 0; i < NUM_ROW; i++)
   LoadedMap[i] = new char[NUM_COLS];

// Then read one line at a time
string buf;
for (int i = 0; i < NUM_ROW; i++) {
   getline(infile, buf);
   memcpy(LoadedMap[i], buf.c_str(), NUM_COL);
}

// Sometime later, you should free the memory


for (int i = 0; i < NUM_ROW; i++)
   delete LoadedMap[i];

delete LoadedMap;

Upvotes: 1

Related Questions