我有一个项目要做,就是迷宫游戏。
为了设置字段,我使用了
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/