2

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!!

Sudhir kumar
  • 549
  • 2
  • 8
  • 31
  • 2
    Read *carefully* [scanf(3)](http://man7.org/linux/man-pages/man3/scanf.3.html). You should test its return value (count of successfully read items). – Basile Starynkevitch Oct 24 '14 at 12:29
  • possible duplicate of [Strange things happening while trying to read strings from keybord](http://stackoverflow.com/questions/29905009/strange-things-happening-while-trying-to-read-strings-from-keybord) – ericbn Apr 27 '15 at 21:01

1 Answers1

7

You are leaving a newline \n character in the buffer everything you press enter to input a character. On every other iteration scanf reads that newline.

" %c" the space before the %c will consume whitespace including the newline. if there is one.

2501
  • 25,460
  • 4
  • 47
  • 87