1
#include<stdio.h>

int main()
{
char a[10];
for(int i=0; i<5; i++)
{
   printf("\nEnter a character: ");
   scanf("%c",&a[i]);
}

}

In this loop, the program first asks the question normally. But in the second loop the program doesn't give me option to input a character and immediately runs the third loop.

Likewise, all the even iterations are skipped.

Aditya
  • 757
  • 1
  • 12
  • 23
  • 2
    If you are pressing enter after each character you need to consume the trailing new-line lefted by `scanf`: `scanf(" %c",&a[i]);` notice a white-space before `%` – David Ranieri Nov 15 '16 at 09:07
  • In the linked FAQ, scroll down to "When *scanf() does not work as expected". – Lundin Nov 15 '16 at 09:48

3 Answers3

1

I agree with @Keine

You should be able to get the expected output by adding a space before the %

Corrected code

#include<stdio.h>

int main()
{
char a[10];
for(int i=0; i<5; i++)
{
   printf("\nEnter a character: ");
   scanf(" %c",&a[i]);
}

}

SOURCE https://gsamaras.wordpress.com/code/caution-when-reading-char-with-scanf-c/

Mihir Kale
  • 1,028
  • 1
  • 12
  • 20
0

There is a newline character at the end of the input get rid of it.

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

Notice the space before %c

Gopi
  • 19,784
  • 4
  • 24
  • 36
0

You may be entered a "Return" key just after a character. This means a line-feed character also has been supplied to the program. That's what happened to the program.

To avoid this use fgets() and sscanf().

#include<stdio.h>

int main()
{
    int i;
    char a[10], buf[10];
    for(i=0; i<5; i++)
    {
        printf("%d) Enter a character: ", i);
        fflush(stdout);
        fgets(buf, 10, stdin);
        sscanf(buf, "%c", &a[i]);
    }

    for(i=0; i<5; i++)
    {
        printf("%d) Entered character: %c\n", i, a[i]);
    }
}

Output:

0) Enter a character: a
1) Enter a character: b
2) Enter a character: c
3) Enter a character: d
4) Enter a character: e
0) Entered character: a
1) Entered character: b
2) Entered character: c
3) Entered character: d
4) Entered character: e

fflush() in the code not necessary in unix like system.