简体   繁体   English

编译器不会在scanf()上停止输入

[英]Compiler doesn't stop on scanf() for input

This is a small C code 这是一个小的C代码

  #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). 我第一次输入'Y'作为输入(没有qoutes),循环返回true并第二次进入循环,但这一次它没有在scanf()上停止供用户输入。(请使用为清楚起见,“ Y”)。 The output is shown below : 输出如下所示:

在此处输入图片说明

As shown here, the compiler didn't stop for input for the second time. 如此处所示,编译器没有第二次停止输入。 What is the reason behind this. 这背后的原因是什么? Thanks in advance ! 提前致谢 !

Just put a space in the scanf like this: 像这样在scanf中放置一个空格:

scanf(" %c",&ch);

And the reason is you enter: Y\\n (with the enter) 原因是您输入: Y\\n (使用回车键)
scanf only reads Y ! scanf仅读取Y So in the next scanf \\n is still in the buffer and get's read in! 因此,在下一个scanf \\n仍在缓冲区中并读入!

So if you now have a space before you read something new it makes a cut (and it looks like this: '\\n ')! 因此,如果您在阅读新内容之前有一个空格,它会被切掉(看起来像这样:'\\ n')!

'\\n' automatically becomes the input for the next iteration. '\\n'自动成为下一次迭代的输入。

To avoid this use getchar() . 为了避免这种情况,请使用getchar() It will take care of the unwanted '\\n' . 它将处理不需要的'\\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 _

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM