问题
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
inscanf(" %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