编译器不会在scanf()上停止输入 [英] Compiler doesn't stop on scanf() for input

查看:163
本文介绍了编译器不会在scanf()上停止输入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是一个小的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;
  }

我第一次输入'Y'作为输入(没有qoutes),循环返回true并第二次进入循环,但这一次它没有在scanf()上停止供用户输入.(请执行为清楚起见,输入为"Y").输出如下所示:

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 :

如此处所示,编译器没有第二次停止输入.这背后的原因是什么?预先感谢!

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

推荐答案

只需在scanf中放置一个空格,如下所示:

Just put a space in the scanf like this:

scanf(" %c",&ch);

原因是您输入:Y\n(使用回车键)
scanf仅读取Y!因此,在下一个scanf中,\n仍在缓冲区中并被读取!

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!

因此,如果您在阅读新内容之前有一个空格,则会进行裁切(看起来像这样:'\ n')!

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

这篇关于编译器不会在scanf()上停止输入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆