Program Explantion:- I have written a program which takes character input from the user infinite no. of times and print the entered input.Here is the program
#include<stdio.h>
int main()
{
int i=1;
char a;
while (i!=0)
{
printf("Enter %d th value\n",i);
scanf("%c",&a);
printf("Entered input is %c\n",a);
i++;
}
}
Output of the above program:-
Enter 1 th value
q
Entered input is q
Enter 2 th value
Entered input is
Enter 3 th value
r
Entered input is r
Enter 4 th value
Entered input is
Enter 5 th value
g
Entered input is g
Enter 6 th value
Entered input is
Enter 7 th value
As you can see the program is skipping the even numbered loops and it is working for only odd number of 'i' values.
What I have Done:-
I have searched the Internet my whole day and at last I found out that we have to insert space before %c in scanf.Here is the updated program.
#include<stdio.h>
int main()
{
int i=1;
char a;
while (i!=0)
{
printf("Enter %d th value\n",i);
scanf(" %c",&a); //changed lineeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeee
printf("Entered input is %c\n",a);
i++;
}
}
I made no difference but I have added space before %c in scanf .Now it is working fine.Here is the output:-
Enter 1 th value
q
Entered input is q
Enter 2 th value
w
Entered input is w
Enter 3 th value
e
Entered input is e
Enter 4 th value
r
Entered input is r
Enter 5 th value
My Question:- What is happening exactly? I am very eager to know about the problem.Can some one explain me in detail.I surfed through the internet but I did not find any explanation about this kind of problem!!