【问题标题】:Scanf Skip scanning character [duplicate]Scanf 跳过扫描字符[重复]
【发布时间】:2016-03-29 10:35:51
【问题描述】:

我的问题是字符的 scanf 被跳过并且它不检查扫描字符以查看我是否想再次重复该程序,为什么会发生这种情况?

#include <stdio.h>
#include <stdlib.h>

int main()
{

    int number,check;
    char rep;

    printf("Program to check if number is even or odd");

    while( (rep!='N') || (rep!='n') )
    {
        printf("\n\nPlease enter the number: ");
        scanf("%d",&number);

        check = number%2;

        if(check != 0)
            printf("\nNumber is odd.");
        else
            printf("\nNumber is even.");
        printf("\n");

        printf("Do you want to enter number again?\nY=yes\tN=no\n");
        scanf("%c", &rep);
    }


    return 0;
}

【问题讨论】:

  • 这里有数百个(甚至可能是数千个)重复项,但问题的要点是,在您读取数字后,换行符仍在输入缓冲区中。猜猜下一个scanf 电话会读到什么......
  • char rep=0;...while(rep!='N' &amp;&amp; rep!='n'){

标签: c scanf


【解决方案1】:

scanf("%c", &amp;rep); 更改为scanf(" %c", &amp;rep);

这是因为第一次输入数字时,stdin 中会留下一个“\n”。执行scanf("%c", &amp;rep); 时,该'\n' 立即被scanf() 使用并分配给rep。由于 '\n' 既不等于 'N' 也不等于 'n',所以循环继续。

使用格式字符串中的前导空格,所有空白字符在读取开始前都会被丢弃。在您的情况下,不可见的 '\n' 将被忽略,以便您可以输入字符。

另外,您应该改写char rep = 0;,以防rep 的原始值恰好是“n”或“N”。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-01-31
    • 2015-12-15
    • 1970-01-01
    • 1970-01-01
    • 2013-01-07
    • 2022-11-24
    相关资源
    最近更新 更多