1

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;
}
BLUEPIXY
  • 39,699
  • 7
  • 33
  • 70

2 Answers2

5

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?

P.P
  • 117,907
  • 20
  • 175
  • 238
0
#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.

DevMJ
  • 2,810
  • 1
  • 11
  • 16