-2

In following c code scanf is not working. When program is run, it execute upto the second printf line and after it skips the scanf("%c",&sex); and directly execute next printf(). Why this so happen? I run this code on different c compilers, but the output is same.

#include<stdio.h>
void main()
{
  char mar,sex;
  int age,flag=0;

  printf("Married [Y/N]:");
  scanf("%c",&mar);

  printf("Sex [M/F] :");
  scanf("%c",&sex);   //**This not working**

  printf("Age :"); //**execution directly jumped here**
  scanf("%d",&age);

  if(mar=='y')
    flag=1;
  else if(sex=='m'&& age>=30)
    flag=1;
  else if(sex=='f'&& age>=25)
    flag=1;
  else
  {
  }
  if(flag)
  {
    printf("Congratulations!!!! You are Egligible..");
  else
    printf("Sorry... You are not egligible..");

getch();
}

//Output

Married [Y/N]:y
Sex [M/F] :Age :23
Congratulations!!!! You are Egligible..
Parikshit Chalke
  • 3,745
  • 2
  • 16
  • 26

1 Answers1

0

The problem is with the new line character that you press after you enter values (Y/N) for the previous scanf. The new line character is taken as an input and the program proceeds with the next one. Try to use flushall(); before next read (that is scanf) this will solve your problem. You can also use space before the format specifier to solve this, that will escape the newline character.

iamrameshkumar
  • 1,328
  • 1
  • 14
  • 34