getchar()在C中不起作用

时间:2016-03-16 21:46:21

标签: c getchar

我正在使用getchar()来获取C中的单词并使用开关来知道输入是什么,但它不等待输入。谁能告诉我为什么会这样?

这是我的代码:

#include <stdio.h>
#include <math.h>
int main()
{
    printf("Written By A.Rahbari\n");
    float velocity_ratio_of_sun_and_planet ;
    float velocity_ratio_double_gear;
    float N_Annulus;
    float N_Sun;
    float N_Planet;
    float u;
    int x;
    int y;
    int i;
    int g;
    printf("Enter velocity ratio of sun and planet:\n");
    scanf("%f",&velocity_ratio_of_sun_and_planet);
    printf("Enter velocity ratio of double gear:\n");
    scanf("%f",&velocity_ratio_double_gear);
    printf("Enter sun or annulus:");
    g=getchar();
    switch(g)
    {

    case '10' :
        printf("your design is based on annulus\n");
        printf("Enter range of annulus teeth per inch:\n");
        scanf("%d%d",&x,&y);
        printf("Enter nember of range step:\n");
        scanf("%d",&i);
        for (N_Annulus=x; N_Annulus<=y; N_Annulus+=i)
        {
            N_Sun = N_Annulus / (velocity_ratio_of_sun_and_planet - 1);
            N_Planet=( N_Annulus - N_Sun )/2;
            u=(N_Sun - floor(fabs(N_Sun)))+(N_Planet - floor(fabs(N_Planet)));
            printf("g");
            if (u == 0)
            {
                printf("\t%d\t\t   %d\t\t %d\t\t\n",N_Annulus,N_Sun,N_Planet);
            }
            else
            {
                continue;
            }
         }
         break;

    case 's':

        break;
    }

    return 0;
}

2 个答案:

答案 0 :(得分:1)

此处getchar() 等待,因为最后一个scanf()将换行符(\n)留在输入缓冲区中,因为最后一个ENTER键按下了scanf()输入。

如果您希望getchar() 等待进行用户输入,则需要先清除缓冲区,然后才能拨打getchar()

答案 1 :(得分:0)

而是g = getchar();尝试scanf("%c",&g);