gpt4 book ai didi

c - C语言中如何将文本文件中的字符放入数组中

转载 作者:行者123 更新时间:2023-11-30 21:02:29 25 4
gpt4 key购买 nike

我有一个项目要做,就是迷宫游戏。

为了设置字段,我使用了

const char random_field[15][20]={
"####################",
"#...#.....#.....#.?#",
"#.#.#.....#.#.....##",
"#.#.#####.#.#.######",
"#.#.#.......#.#.####",
"#.#.###.#######.####",
"#.#................#",
"#.####...#####.###.#",
"#.#....####..#.###.#",
"#.#.#........#.#...#",
"#.#.####..####.#.###",
"#.#....#.....#.#...#",
"#.######.#####.###.#",
"#..................#",
"####################"
};

而且效果很好!

但现在我想稍微改变一下想法..

我想把这个 map 写入一个文本文件,然后声明一个二维数组,并将txt文件中的 map 固定到数组中。

我已经写了这个,但它不起作用..

const char random_field[15][20] ;
FILE *filename;

filename=fopen("map1.txt","r");

for (i = 0; i < 15; i++)
{
for (j = 0; i < 20; j++)
{
fscanf(filename, "%c", &random_field[i][j]);
}

}

for (i = 0; i < 15; i++)
{
for (j = 0; i < 20; j++)
{
printf("%c",random_field[i][j]);
}

}

有什么想法吗?谢谢

最佳答案

您有一些小拼写错误,并且没有正确处理新行。

filename=fopen("map1.txt","r");

for (i = 0; i < 20; i++)
{
//// You had i < 20 here.
for (j = 0; j < 20; j++)
{
fscanf(filename, "%c", &random_field[i][j]);
}
// Each row in the text file has a new line character on the end
// so scan for this.
fscanf(filename, "\n");
}

for (i = 0; i < 15; i++)
{
//// You had i < 20 here.
for (j = 0; j < 20; j++)
{
printf("%c",random_field[i][j]);
}
// You need to add a new line in the print out after each row
// since it isn't mistakenly in random_field now.
printf("\n");
}

通过您的代码,您将新行字符(或多个字符)读入每个 random_field 的第一行,而不是跳过它。

关于c - C语言中如何将文本文件中的字符放入数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29480601/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com