将2D数组保存到文件c ++

时间:2014-04-06 20:27:37

标签: c++ arrays file multidimensional-array

我正在尝试将2D数组保存到文件中,但我们将其显示为" ^ L"。如果用户输入Y或y,则该程序应该结束,但它正在打印我的2D数组。

//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";

2 个答案:

答案 0 :(得分:2)

可以执行类似这样的操作,将地图序列化为流。流可以由您指定。 std::coutstd::fstream可以正常工作..

#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();
    }
}

以上将把地图写入文件以及屏幕..

结果将是:

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

答案 1 :(得分:1)

您所做的就是序列化。

您有两种选择。

  1. 使用像boost这样的库为您执行此操作
  2. 让你自己
  3. 由于你的请求有多简单,我会自己制作。

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

    此代码未编译或测试!