c - Formatting issue with fgets in a function -


i asking input functions using fgets. keep getting annoying bug, in program skips right on input , goes input of second variable. have no idea seems problem. code in question below. reads getchar(), , if 'n' goes 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 whole output):

>n >name: age:  

this works now

printf("name: "); while(getchar()!='\n');  fgets(name, 20, stdin); 

that's because stdin buffer has newline buffered in it. remove it, use :

fflush(stdin); 

so code 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, here says discouraged use fflush(stdin); (although had worked me everytime. :) ) here solution. instead of fflush(stdin) use:

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

that empty buffer newline may skip next fgets call.


Comments

Popular posts from this blog

c# - SharpSVN - How to get the previous revision? -

c++ - Is it possible to compile a VST on linux? -

url - Querystring manipulation of email Address in PHP -