阅读和检查字符问题

时间:2009-09-12 01:47:53

标签: c++

这是我的代码

#include<stdio.h>

int main()
{

    char choice;

    printf("Do you want to enter a number:");
    scanf("%c",&choice);

    while(choice == 'y')
    {
      printf("Entered number\n");
      printf("Do you want to enter a number:");
      scanf("%c",&choice);


    }

    printf("End\n");

return 0;
}

,输出

Do you want to enter a number:y
Entered number
Do you want to enter a number:End

第一次检查我的角色是否为'y',但是在第一次执行后的循环中,它不等待用户输入,它只是终止循环。可能出了什么问题?请帮忙

1 个答案:

答案 0 :(得分:1)

看看 - http://faq.cprogramming.com/cgi-bin/smartfaq.cgi?answer=1044873249&id=1043284392

#include<stdio.h>

int main()
{
    char choice;

    printf("Do you want to enter a number:");
    scanf("%c",&choice);

    while (choice == 'y')
    {
        while ((choice = getchar()) != '\n' && choice != EOF);
        printf("Entered number\n");
        printf("Do you want to enter a number:");
        scanf("%c",&choice);
    }

    printf("End\n");

    return 0;
}

不要使用: fflush Why fflush(stdin) is wrong