简体   繁体   中英

how can input txt file to 2d array completely at C

I'm trying to get txt file to 2d array. But some values at the back are missed. I wonder why this happening.

this is txt file's form I want to get

#define MAZE_ROW 11
#define MAZE_COL 22

char maze[MAZE_ROW][MAZE_COL];
int main(){
    Get_Maze();
    Print_Maze();
}

void Get_Maze(){
    FILE *f=fopen("maze.txt","r");
    for(int i=0;i<MAZE_ROW;i++){
        for(int j=0;j<MAZE_COL;j++){
                fscanf(f,"%c",&maze[i][j]);
        }
    }
    fclose(f);
}

void Print_Maze(){
    for(int i=0;i<MAZE_ROW;i++){
        for(int j=0;j<MAZE_COL;j++){
            printf("%c",maze[i][j]);
        }
    }
}

this is the result of my code

the problem is with the '\n' - newline characters. In your text file, at the end of every line, there is a '\n', and by using fscanf(f,"%c",&maze[i][j]); , you are not skipping any whitespaces (space, tab, newline character, etc) and thus your code skips the last few 0|1 in your text file, since some of its values are already assigned to '\n' and the maze[MAZE_ROW][MAZE_COL] variable has too few mebers.

A quick fix would be to use for example:

fscanf(f," %c",&maze[i][j]); (with space before %c) - this will cause fscanf to ignore any whitespaces, in your case the '\n', and it will only load the characters you wanted to.

Problem is that this will cause your output to be in a single line, since you are not printing any new line, so the last thing is to change your Print_Maze() to this

void Print_Maze(){
    for(int i=0;i<MAZE_ROW;i++){
        for(int j=0;j<MAZE_COL;j++){
            printf("%c",maze[i][j]);
        }
        printf("\n");
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM