savannaalexis
savannaalexis

Reputation: 65

saving a 2D array to a file c++

I am trying to save a 2D array into a file, but it us showing up as "^L". If the user enters Y or y, then the program is supposed to end, but it is printing my 2D array instead.

//Allow user to quit
cout << "Would you like to quit this game? Enter Y or N: " << endl;
cin >> Choice;
if (Choice == 'Y' || Choice == 'y')
{
   ofstream outfile("Map.txt");
   for (int row = 0; row < ROWS; row++)
   {
       for (int col = 0; col < COLS; col++)
         outfile << "Here is your map! " << Map[ROWS][COLS] << endl;
   }
   outfile.close();
}

if (Choice == 'N' || Choice == 'n')
{
    // Add code to play the game
    PlayTurn(TreasureR, TreasureC, Row, Col, NumMoves);
}
// Print the map for true
PrintMap(Map,true, TreasureR, TreasureC, StartR, StartC, Row, Col);

//End the game
cout << "You finished the Game in  " << NumMoves <<" moves.\n";

Upvotes: 1

Views: 14745

Answers (2)

andre
andre

Reputation: 7249

What your doing is called serialization.

You have two options.

  1. Use a library like boost to do this for you
  2. Make you own

Because of how simple your request is I would make my own.

std::ostream& serialize(std::ostream& outfile, int** arr, int rows, int cols) {
    outfile << rows << " ";
    outfile << cols << " ";
    for (int i = 0; i < rows; i++)
        for(int j = 0; j < cols; j++)
            outfile << arr[i][j] << " ";
    return outfile;
}

int** deserialize(std::istream& file, int& rows, int& cols) {
    file >> rows;
    file >> cols;
    int** arr = new int*[rows];
    for (int i = 0; i < rows; i++) {
        arr[i] = new int[cols];
        for(int j = 0; j < cols; j++)
            file >> arr[i][j];
    return arr;
}

This code was not compiled or tested!

Upvotes: 1

Brandon
Brandon

Reputation: 23498

Can do something like this to serialize the map into a stream. The stream can be specified by you. std::cout or std::fstream can work..

#include <iostream>
#include <fstream>

template<typename T, int height, int width>
std::ostream& writemap(std::ostream& os, T (&map)[height][width])
{
    for (int i = 0; i < height; ++i)
    {
        for (int j = 0; j < width; ++j)
        {
            os << map[i][j]<<" ";
        }
        os<<"\n";
    }
    return os;
}

int main()
{
    const int width = 4;
    const int height = 5;

    int map[height][width] =
    {
        {1, 2, 3, 4},
        {5, 6, 7, 8},
        {9, 10, 11, 12},
        {13, 14, 15, 16},
        {17, 18, 19, 20}
    };

    std::fstream of("Map.txt", std::ios::out | std::ios::app);

    if (of.is_open())
    {
        writemap(of, map);
        writemap(std::cout, map);
        of.close();
    }
}

The above will write the map to a file as well as to the screen..

The result will be:

1 2 3 4 
5 6 7 8 
9 10 11 12 
13 14 15 16 
17 18 19 20 

Upvotes: 2

Related Questions