Aditya Aditya - 23 days ago 7
C Question

Why does my loop skip even steps?

#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.

Answer

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/