使用控制台程序键盘输入去除回车干扰

      在使用控制台程序练习键盘输入时,会产生回车干扰。代码如下

#include <stdio.h>

int main(void)
{
    char ch = ' ';
    while(ch != 'n')
    {
        printf("If you input 'n', the circle ends.\n");
        ch = getchar();
    }
    return 0;
}

      当在控制台程序中输入某个字母,例如 'm',然后回车,会出现两次提示:

If you input 'n', the circle ends.

If you input 'n', the circle ends.

     这是因为输入回车后,回车会存入缓冲区,当执行下次循环时,回自动赋值给 ch。

解决方法1:将这个回车赋值给另一个字符变量。

#include <stdio.h>

int main(void)
{
    char chm = ' ';
    char ch = ' ';
    while(ch != 'n')
    {
        printf("If you input 'n', the circle ends.\n");
        ch = getchar();
        chm = getchar();
    }
    return 0;
}

 

解决方法2:flush 掉缓冲区的回车

#include <stdio.h>

int main(void)
{
    char ch = ' ';
    while(ch != ' ')
    {
        printf("If you input 'n', the circle ends.\n");
        ch = getchar();
        fflush(stdin);
    }
    return 0;
}

 

posted @ 2012-12-30 23:11  林燃  阅读(470)  评论(4编辑  收藏  举报