【问题标题】:getchar() doesn't work in C [duplicate]getchar() 在 C 中不起作用 [重复]
【发布时间】:2016-03-16 21:46:21
【问题描述】:

我正在使用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;
}

【问题讨论】:

  • 基本规则:如果您的输入是基于行的,则使用基于行的函数。看fgets

标签: c getchar


【解决方案1】:

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

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

【讨论】:

  • 如果每次有人犯这个错误我只能得到一分钱:)
【解决方案2】:

改为g = getchar(); 试试scanf("%c",&amp;g);

【讨论】:

  • 请详细说明这是如何回答问题的。
猜你喜欢
  • 2015-09-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-07
  • 2018-06-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多