Compiler doesn't stop on scanf() for input

2019-06-10 23:12发布

This is a small C code

  #include<stdio.h>
  int main()
  {
    char ch='Y';
    while(ch=='Y')
    {
      printf("\nEnter new value for Y ");
      scanf("%c",&ch);
      if(ch=='Y' || ch=='y')
        // do some work 
        printf("Y was selected\n");
    }
    printf("exiting main");
    return 0;
  }

I entered 'Y' as input (without qoutes) for the first time, the loop returned true and came inside for the second time, but this time it didn't stop on scanf() for user input.(Please execute with input as 'Y' for clarity). The output is shown below :

enter image description here

As shown here, the compiler didn't stop for input for the second time. What is the reason behind this. Thanks in advance !

2条回答
别忘想泡老子
2楼-- · 2019-06-10 23:38

'\n' automatically becomes the input for the next iteration.

To avoid this use getchar(). It will take care of the unwanted '\n'.

#include<stdio.h>
  int main()
  {
    char ch='Y';
    while(ch=='Y')
    {
      printf("\nEnter new value for Y ");
      scanf("%c",&ch);

      getchar();  //takes care of '\n'

      if(ch=='Y' || ch=='y')
        // do some work 
        printf("Y was selected\n");
    }
    printf("exiting main");
    return 0;
  }

the code works fine now. Below is the snippet from the command window.

Enter new value for Y Y
Y was selected

Enter new value for Y Y
Y was selected

Enter new value for Y _
查看更多
霸刀☆藐视天下
3楼-- · 2019-06-10 23:44

Just put a space in the scanf like this:

scanf(" %c",&ch);

And the reason is you enter: Y\n (with the enter)
scanf only reads Y! So in the next scanf \n is still in the buffer and get's read in!

So if you now have a space before you read something new it makes a cut (and it looks like this: '\n ')!

查看更多
登录 后发表回答