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;

}
4
  • 1
    The correct solution depends on whether you are using C or C++. They are not the same language! Commented Mar 2, 2014 at 13:14
  • Which compiler are you using? Commented Mar 2, 2014 at 13:16
  • @ChristianHackl i am using simple c..please help Commented Mar 2, 2014 at 13:16
  • @user3370739: then please consider removing the C++ tag. Commented Mar 2, 2014 at 13:18

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

3 Comments

instead of using getch(), it's safer to use fflush(stdin)
@Abishek result is the same
@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 for a more thorough explanation and an albeit nonportable workaround. But your workaround works too, +1
0

Another option is to

scanf(" %c", &location);

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.