程序循环两次(打印语句两次)

Program looping two times (printing statement twice)

我正在尝试制作一个简单的程序,用户应该为其输入字符 'a'。它应该循环直到输入 'a' 。如果没有正确工作的输入,我会打印一份声明。如果输入了错误的字母或数字,还有另一个语句,但问题是这会导致程序循环不止一次,并多次打印语句。感谢任何解决此问题的帮助。

#include <stdio.h>

int main()
{
    char input;
    int i, len,num;
    len = 1;

    do
    {
        puts("Please enter alphabet 'a': ");
        scanf("%c", &input);
        for(i=0; i<len; i++)
        {
            if(isalpha(input)==0)
            {
                printf("Please input something.\n");
                continue;
            }
            if(input == 'A' || input == 'a')
            {
                printf("Congratulations! You successfully input letter 'a'.");
                return(0);
            }
            else
            {
                printf("That's not letter 'a'.");
            }
        }
    }
    while(1);
}

第一个输入后缓冲区中有一个换行符未被刷新,并且在第二次迭代中被 %c 拾取。

将您的 scanf() 更改为

scanf(" %c", &input);

注意 %c 之前的 space 吞噬了换行符

问题是输入字符后,你按换行符,这被发送到输入缓冲区。现在下一次调用 scanf() 时,它会从缓冲区中读取 '\n' 的值,然后 scanf() 将其存储到 input。现在可以通过@Gopi 指出的方法轻松解决,但还有更好的方法。这是代码。

#include <stdio.h>
#include<ctype.h>

int main()
{
    char input,ch;

    do
    {
        puts("Please enter alphabet 'a': ");
        scanf("%c", &input);
        while( input!='\n' && (ch=getchar())!='\n' && ch!= EOF);   // look here

            if(isalpha(input)==0)
            {
                printf("Please input something.\n");
                continue;
            }
            if(input == 'A' || input == 'a')
            {
                printf("Congratulations! You successfully input letter 'a'.");
                return(0);
            }
            else
            {
                printf("That's not letter 'a'.");
            }

    }
    while(1);
}

现在使用语句while((ch=getchar())!='\n' && ch!= EOF);,像'\n'这样的所有字符都只是刷新而不存储到input,从而解决了问题。

另请注意,此处不需要 for 循环,它对这段代码毫无用处(除非这不是您的原始代码并且其中还有其他部分)。