Why Scanf works wierd while taking a character

℡╲_俬逩灬. 提交于 2019-12-24 05:12:25

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/26547850/why-scanf-works-wierd-while-taking-a-character

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!