Character blanking in c

code

int main()
{
     int n,m,i,j;char a[10][10];
     printf("enter n and m values\n");     
     scanf("%d%d",&n,&m);

     printf("enter array values");    
     for(i=0;i<n;i++)
        for(j=0;j<m;j++)
          scanf("%c",&a[i][j]);

     printf("the array is \n");
     for(i=0;i<n;i++)
        for(j=0;j<m;j++)
          printf("%d %d %c\t",i,j,a[i][j]);
}

Enter

 Enter n and m values  
 4 5
 Enter characters 
 11111000001111100000

Output

0 0 

0 1 1   0 2 1   0 3 1   0 4 1   1 0 1   1 1 0   1 2 0   1 3 0   1 4 0   2 0 0    
2 1 1   2 2 1   2 3 1   2 4 1   3 0 1   3 1 0   3 2 0   3 3 0   3 4 0   

Error

If I give n as 4 and m as 5, scanf does this job.

But when printing, when the value of i is 0 and j is 0, it does not print anything.

Meanwhile, a [0] [1] prints the first input, and [0] [2] prints the second input and sequentially, so the last input 0 is missing during printing.

Please explain why avoid [0] [0].

+4
source share
1 answer

Previous calls scanfleave a character \nin the input buffer, which comes with input when you press the Enteror key Return. scanf("%c",&a[i][j]);reads that \nin the first iteration.

. %c scanf

scanf(" %c", &a[i][j]);   
       ^A space before `%c` can skip any number of leading white-spaces

int c;
while((c = getchar()) != '\n' && c != EOF);  

: fflush(stdin) ?

fflush . "" , ( ), fflush .

: c-faq 12.18.

+5

Source: https://habr.com/ru/post/1546701/


All Articles