Search code examples
cformattingfgets

Formatting issue with fgets in a function


I am asking for input from a functions using fgets. I keep getting a annoying bug, in which the program skips right over the input and goes to input of the second variable. I have no idea what seems to be the problem. The code in question is below. It reads from getchar(), and if it is 'n' it goes the 2nd function.

#include <stdio.h>

void enter(){
    char name[20];

int Age;
float Highbp;
float Lowbp;

    printf("name: ");
    fgets(name, 20, stdin);

    printf("age: ");
    scanf("%d", &Age);

    printf("high bp: ");
    scanf("%f", &Highbp);

    printf("low bp: ");
scanf("%f", &Lowbp);


    return ;

    }
    void option(){

        char choice = getchar();

        if(choice == 'n'){

        enter();
        }
    }
int main(int argc, char **argv)
{

option();
}

output produced (not the whole output):

>n
>name: age: 

This works now

printf("name: ");
while(getchar()!='\n');

fgets(name, 20, stdin);

Solution

  • That's because the stdin buffer has a newline buffered in it. To remove it, use :

    fflush(stdin);
    

    So your code is now like this:

    #include <stdio.h>
    
    void enter(){
    char name[20];
    
    int Age;
    float Highbp;
    float Lowbp;
    
    printf("name: ");
    fflush(stdin);
    fgets(name, 20, stdin);
    
    printf("age: ");
    scanf("%d", &Age);
    
    printf("high bp: ");
    scanf("%f", &Highbp);
    
    printf("low bp: ");
    scanf("%f", &Lowbp);
    
    
    return ;
    
    }
    void option(){
    
        char choice = getchar();
    
        if(choice == 'n'){
    
        enter();
        }
    }
    int main(int argc, char **argv)
    {
    
    option();
    }
    

    Edited

    Since, everybody here says that it is discouraged to use fflush(stdin); (Although it had worked for me everytime. :) ) Here is another solution. Instead of fflush(stdin) use:

    while(getchar()!='\n');
    

    That will empty the buffer for the newline that may skip next fgets call.