1

Hello i am beginner in programmin. I have simple issue. When i take user input. I was asked Enter Your Age: then after entering age i was asked(problem is here: why it's executing two linesc) "Enter c for city and v for village: Enter 'h' for healthy and 'p' for poor health: "

and cursor comes after health:

It should ask for "Enter c for city and v for village:" first. I have tried alot. Please help me

int main(){
int age;
char sex;
char location;
char health;

printf("Enter Your Age: ");
scanf("%d",&age);
printf("Enter c for city and v for village: ");
scanf("%c", &location);
printf("Enter 'h' for healthy and 'p' for poor health: ");
scanf("%c", &health);
printf("Enter 'm' for male and 'f' for female: ");
scanf("%c", &sex);


if(age>=25 && age<=35){

  printf("hello ahmed ");
}
    else{
         printf("Sorry You Cannot Be Insured ");
}


getch();
return 0;

}
tenfour
  • 36,141
  • 15
  • 83
  • 142

2 Answers2

1

It seems when you enter your age, the 'enter' remains in the buffer and gets read into location.

printf("Enter Your Age: ");
scanf("%d",&age); 
printf("Enter c for city and v for village: ");
scanf("\n%c", &location); // add this line to ignore the newline character.

EDIT: fflush() removed because it seems it works only for output streams and not input. IMO Better is to first read the newline character and then the actual location character.

Abhishek Bansal
  • 12,589
  • 4
  • 31
  • 46
  • instead of using `getch()`, it's safer to use `fflush(stdin)` – fvu Mar 02 '14 at 13:20
  • @Abishek result is the same – user3370739 Mar 02 '14 at 13:22
  • @AbhisshekBansal Indeed the behaviour of fflush on input streams is not standardized (ie, it's not guaranteed to work), sorry for that. See [this SO question](http://stackoverflow.com/questions/2187474/i-am-not-able-to-flush-stdin) for a more thorough explanation and an albeit nonportable workaround. But your workaround works too, +1 – fvu Mar 02 '14 at 14:48
0

Another option is to

scanf(" %c", &location);

include a space before the %c for it to ignore the white space or new line.

Joe
  • 1,312
  • 20
  • 24