【问题标题】:How do I output a 2d array correctly in c++ with if states within?如何在 c++ 中正确输出带有 if 状态的二维数组?
【发布时间】:2021-02-26 14:36:02
【问题描述】:

我必须为 2d 迷宫游戏编写代码,并在终端中输出。 所以我的问题是我有一个包含 6 个值的文本文件(目标索引、数组的开始和最大大小),看起来像这样

5 7
2 0
2 6
*******
* * * *
  *
*   ***
*******

我已经有了正确的输出,但是如果我想用一个字符替换其中一个空格来标记起点,我会得到这个

 *******
* * *S*
  *
*   ***

这是我的代码:

ifstream mazeFile("mazeExample.txt", std::ios_base::in);
int height, width, heightStart, widthStart, heightGoal, widthGoal;
int playerX, playerY;

void readMaze(){
char map[height][width];

mazeFile >> height;
mazeFile >> width;
mazeFile >> heightStart;
mazeFile >> widthStart;
mazeFile >> heightGoal;
mazeFile >> widthGoal;

for (int y = 0; y < height; y++)
{
    for (int x = 0; x < width; x++)
    {
        mazeFile.get(map[y][x]);
        if (!(x == widthStart && y == heightStart))
        {
        }else{
            map[y][x] = 'S';
        }
        cout << map[y][x];
    }
}

我不明白为什么它在中间插入“S”而不是替换给定索引处的空格。其他解决方案没有奏效,我不想只是复制他们的代码。

【问题讨论】:

  • char map[height][width] 肯定是错误的,因为此时您甚至没有为heightwidth 赋值。
  • 我已经尝试在 ifstream 分配值后初始化我的 char 映射,但仍然无法解决
  • char map[height][width]; -- 首先,这不是有效的 C++ 代码。 C++ 中的数组的大小必须由编译时值表示,而不是运行时值。使用std::vector&lt;std::vector&lt;char&gt;&gt; map(height, std::vector&lt;char&gt;(width)); 可以轻松完成动态二维数组。

标签: c++ multidimensional-array


【解决方案1】:

哇,至少你很勇敢!

// creates a 2D Variable Length Array with current values for height and width
char map[height][width];
// loads (but a bit late) the values for the variables which have just been used above
mazeFile >> height;
mazeFile >> width;

更严重的是,这是一段糟糕的 C++ 代码。 VLA 在标准 C++ 中不受支持,仅作为 gcc 的扩展支持。此外,它们通常被避免,因为它们可能不是异常安全的。最后但并非最不重要的一点是,尺寸在在声明时使用。

在这里做什么:

  1. 最低限度是仅在数组的维度已知时才声明该数组

     void readMaze(){
    
     mazeFile >> height;
     mazeFile >> width;
     char map[height][width];
    

    但这不是符合 C++ 的代码

  2. 或者采用 C++ 的方式,将 C-ish VLA 替换为向量

     cin>>height;
     cin>>width;
     std::vector<std::vector<char>> map(height);
     for(auto v: map) {
         v = std::vector<char>(width);
     }
    

    这是正确的 C++ 代码,应该适用于任何 C++ 系统...

【讨论】:

    猜你喜欢
    • 2017-07-05
    • 2013-01-10
    • 1970-01-01
    • 2013-04-27
    • 1970-01-01
    • 2015-05-10
    • 2021-09-10
    • 2016-02-16
    • 2013-11-30
    相关资源
    最近更新 更多