Reputation: 11
In the output the last character is not printed.
Input: 3 3
abcabcabc
Expected Output: a b c a b c a b c
Actual Output: a b c a b c a b
Where is c???
#include <stdio.h>
int main() {
int i,j,k,n;
char a[3][3],b[3][3];
printf("enter size\n");
scanf("%d %d",&n,&k);
printf("enter character \n");
for(i=0;i<n;i++)
for(j=0;j<k;j++)
scanf("%c",&a[i][j]);
printf("\n");
for(i=0;i<n;i++)
for(j=0;j<k;j++)
printf("%c ",a[i][j]);
return 0;
}
Upvotes: 1
Views: 172
Reputation: 3061
#include <stdio.h>
int main() {
int i,j,k,n;
char a[3][3],b[3][3];
printf("enter size\n");
scanf("%d %d",&n,&k);
printf("enter character \n");
fflush(stdin);
for(i=0;i<n;i++)
for(j=0;j<k;j++)
scanf("%c",&a[i][j]);
printf("\n");
for(i=0;i<n;i++)
for(j=0;j<k;j++)
printf("%c ",a[i][j]);
return 0;
}
Added fflush(stdin) to clear previous newline char (\n) in the input buffer by scanf.
Upvotes: 0
Reputation: 121427
This scanf()
call:
scanf("%d %d",&n,&k);
leaves a newline char (\n
) in the input buffer which is read by the subsequent where you read chars in loop. That's why it takes one less input.
You can add:
int c;
while((c = getchar()) != '\n' && c != EOF);
after scanf("%d %d",&n,&k);
to ignore it. But it's generally accepted that scanf()
is not well-suited for such input reading. So, you might be better off using fgets()
and then parse it.
Relevant: Why does everyone say not to use scanf? What should I use instead?
Upvotes: 5