Reputation: 141
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]);
}
Input
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 the value of n as 4 and m as 5 ,scanf does it job.
But while 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 a[0][2] prints second input and consecutively , so last input 0 is missing while printing.
Please explain why a[0][0] is avoided.
Upvotes: 4
Views: 179
Reputation: 106082
Previous scanf
calls leave behind \n
character in the input buffer which goes along with input on pressing Enter or Return key. scanf("%c",&a[i][j]);
reads that \n
on first iteration.
You need to flush your input buffer. Either place a space before %c
in scanf
scanf(" %c", &a[i][j]);
^A space before `%c` can skip any number of leading white-spaces
or you can use
int c;
while((c = getchar()) != '\n' && c != EOF);
NOTE: Will fflush(stdin)
work in this case?
fflush
is defined only for output streams. Since its definition of "flush" is to complete the writing of buffered characters (not to discard them), discarding unread input would not be an analogous meaning forfflush
on input streams.
Suggested reading: c-faq 12.18.
Upvotes: 5