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

标签 c arrays file

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

为了设置字段,我使用了

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/

相关文章:

c - 将线程策略设置为 SCHED_RR 时出现未知错误

javascript - JS新设置,删除重复不区分大小写?

Python多线程文件处理

python - 文件保存问题 PYTHON - 重复文件?

java.io.StreamCorruptedException : invalid stream header: 00000001 Simple Project

c++ - 您如何获得进程运行了多长时间?

c - 模数或余数 % 有符号值是否始终与 And 运算符从该值减 1 相同?

c - 如何在 C 函数中传递二维数组(矩阵)?

javascript - jQuery Ajax 不将数组作为数据对象发送

php - 我可以将数组绑定(bind)到 PDO 查询中的 IN() 条件吗?