我正在尝试将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";

最佳答案

可以执行类似的操作将地图序列化为流。流可以由您指定。 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

10-08 09:16