【发布时间】: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]肯定是错误的,因为此时您甚至没有为height或width赋值。 -
我已经尝试在 ifstream 分配值后初始化我的 char 映射,但仍然无法解决
-
char map[height][width];-- 首先,这不是有效的 C++ 代码。 C++ 中的数组的大小必须由编译时值表示,而不是运行时值。使用std::vector<std::vector<char>> map(height, std::vector<char>(width));可以轻松完成动态二维数组。
标签: c++ multidimensional-array