-1

I want to take character input using scanf instead of getchar(). So I wrote this coder but each time I input one character value it iterates twice. So I am able to take only 5 inputs. Why is this happening?

#include<stdio.h>

int main() {
    char arr[10];
    for (int i = 0; i < 10; i++) {
        printf("%d:", i);
        scanf("%c", & arr[i]);
        printf("%c", arr[i]);
        printf("\n");
    }
}
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278

1 Answers1

0

You need to consume the trailing newline left by the Enter key when %c is used as format specifier in scanf, otherwise the \n remains in the buffer being consumed as an input/character in the next iteration.

Switch from

scanf("%c", & arr[i]);

to

scanf(" %c", &arr[i]); // Notice a space before %c
David Ranieri
  • 39,972
  • 7
  • 52
  • 94