How do I scan into a 2d char array without scanning in the enter/space chars?

江枫思渺然 提交于 2019-12-12 02:59:33

问题


So I have to make a maze program, and to start I must scan in the maze to a 2d array. The problem arises when i go to put the chars into the array, when the enter char and the space char always take up the first slot in the array...

Here is my code:

    int main(){

    int row, col;

    int i,j,k,l;

    scanf("%d", &row);

    scanf("%d", &col);

    char** maze = (char**) calloc(row, sizeof(char*));

    for ( k = 0; k < row; k++ )
    {
        maze[k] = (char*) calloc(col, sizeof(char));
    }

    for(i=0;i<row;i++){

        for(j=0;j<col;j++){

            scanf("%c",&maze[j][i]);

        }

    }

    for(k=0;k<row;k++){

        for(l=0;l<col;l++){

            printf("%c", maze[k][l]);

        }

        printf("\n");

    }


   return 0;
}

And the output is:

With the enter char:

3

3

xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xx

xxx

xxx

With a space:

3

3 xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xx

xxx

xxx

without any thing: (this one works)

3

3xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx

xxx

xxx

xxx


回答1:


Alright, so as user3121023 commented, putting a space before the %c in
scanf(" %c",&maze[j][i]); works!

The space before the % will skip leading whitespace such as space and enter.




回答2:


You could use getchar() and retry on '\n'. scanf() seems an overkill.

for(i=0;i<row;i++){

    for(j=0;j<col;j++){

        while ( '\n' == (maze[j][i]=getchar() ) );

    }

}


来源:https://stackoverflow.com/questions/36044429/how-do-i-scan-into-a-2d-char-array-without-scanning-in-the-enter-space-chars

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!