c - getchar() 在 C 中不起作用

标签 c getchar

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

这是我的代码:

#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;
}

最佳答案

这里,getchar() 不会等待,因为最后一个 scanf() 留下换行符 (\n) >) 由于 scanf() 输入后最后一次按下 ENTER 键而进入输入缓冲区。

如果您希望 getchar() 等待用户输入,则需要先清理缓冲区,然后才能调用 getchar()

关于c - getchar() 在 C 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36047577/

相关文章:

无法处理连续的 SIGSEGV 信号

c - 加密字符串

c - 逆序打印 AVL 树

c - 我的错误在哪里? (转换基数)

c - 使用命令行参数中的 getchar 和 putchar 来编码程序以发送到解码

c - 为什么 getchar() 在 printf 语句后读取 '\n'?

c - 为什么第一个 gets() 输入在此 C 程序中丢失?

c - 使用 fseek 和 fwrite 覆盖文件中的一行

c - 这个程序有什么作用? (自调用main函数+getchar)

c - 为什么 printf ("%d", getchar()) 打印额外的 10