0

I'm using getchar() to get a word in C and use switch to know what was the input, but it doesn't wait for input. Can anybody tell me why that is?

and this is my code:

#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;
}
Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
  • Basic rule: if your input is line-based, then use line-based functions. Look at `fgets`. – paddy Mar 16 '16 at 21:49

2 Answers2

1

Here, getchar() does not wait because the last scanf() leaves a newline (\n) into the input buffer due to the last ENTER key press after scanf() input.

You need to clean up the buffer before you can call getchar() if you expect getchar() to wait for user input.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261
0

Instead g = getchar(); try scanf("%c",&g);

webpersistence
  • 894
  • 3
  • 12
  • 29