How to put characters in a text file into an array in C programming -
How to put characters in a text file into an array in C programming -
i have project done , maze game.
to set field , have used
const char random_field[15][20]={ "####################", "#...#.....#.....#.?#", "#.#.#.....#.#.....##", "#.#.#####.#.#.######", "#.#.#.......#.#.####", "#.#.###.#######.####", "#.#................#", "#.####...#####.###.#", "#.#....####..#.###.#", "#.#.#........#.#...#", "#.#.####..####.#.###", "#.#....#.....#.#...#", "#.######.#####.###.#", "#..................#", "####################" };
and works !
but want alter thought little bit ..
i want write map text file , declare 2d array , prepare map in txt file array..
i have wrote doesn't work..
const char random_field[15][20] ; file *filename; filename=fopen("map1.txt","r"); (i = 0; < 15; i++) { (j = 0; < 20; j++) { fscanf(filename, "%c", &random_field[i][j]); } } (i = 0; < 15; i++) { (j = 0; < 20; j++) { printf("%c",random_field[i][j]); } }
any ideas ? give thanks you
you have minor typos , aren't handling new lines properly.
filename=fopen("map1.txt","r"); (i = 0; < 20; i++) { //// had < 20 here. (j = 0; j < 20; j++) { fscanf(filename, "%c", &random_field[i][j]); } // each row in text file has new line character on end // scan this. fscanf(filename, "\n"); } (i = 0; < 15; i++) { //// had < 20 here. (j = 0; j < 20; j++) { printf("%c",random_field[i][j]); } // need add together new line in print out after each row // since isn't mistakenly in random_field now. printf("\n"); }
with code, reading new line character (or characters) first row of each random_field rather skipping it.
c arrays file
Comments
Post a Comment