Search code examples
carraysscanfgetchar

Why can't I enter five characters into the array in the first code, but can when using a getchar() as shown in the second code?


I can't enter all the 5 characters into the array if I use the first code. But if I use the second code it works. Why?

Code:1

#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n;
char a[5];
for(i=0;i<5;i++)
{
    printf("%d::",i+1);
    scanf("%c",&a[i]); //I can input only 1,3,5 values.
}
printf("Enter:\n");
for(i=0;i<5;i++)
printf("%c",a[i]);
getch();
return 0;
}

Code:2

#include<stdio.h>
#include<stdlib.h>
int main()
{
int i,n;
char a[5];
for(i=0;i<5;i++)
{
    printf("%d::",i+1);
    scanf("%c",&a[i]);
    getchar();
}
printf("Enter:\n");
for(i=0;i<5;i++)
printf("%c",a[i]);
getch();
return 0;
}

Solution

  • The reason is that when you enter a character, you press the Enter key. scanf will consume the character and then leaves the newline character(\n) in the standard input stream(stdin). When scanf with a %c is called the next time, it sees the newline character persisting in the stdin and directly consumes it, and thus, does not wait for further input.

    In the second code, the getchar() consumes the \n character left over by the previous call to scanf in each iteration. This is why the second code works as expected.