0

Can someone run the following C program on your IDE and advise me what I am missing?.

#include<stdio.h>
#include<conio.h>

int main()
{

    int a;
    char s;
    char n[10];

    printf("What is your name?: ");
    scanf("%s", &n);

    printf("What is your age?: ");
    scanf("%d", &a);

    printf("Are you male or female?: ");
    scanf("%c", &s);

    printf("Your name is %s\nYour age is %d\nYour sex is %c\n", n, a, s);

    getch();
    return 0;

}

While we enter the age and hit the enter button, it slips and shows wrong output without evening asking for the third input "Are you male or female?". I tested it on Turbo C++, Dev C++, Code Blocks, all show the same error output.

enter image description here

Assafs
  • 3,239
  • 4
  • 28
  • 36
vjwilson
  • 560
  • 7
  • 20
  • Possible duplicate of [Second scanf is not working](https://stackoverflow.com/questions/4023643/second-scanf-is-not-working) – Eugene Sh. Sep 22 '17 at 20:47

2 Answers2

3

Your problem is that the scanf("%c", &s); takes the new-line character. Maybe you could try the following scanf(" %c", &s); (important ist the white-space before %c) as described here Problems with character input using scanf() or How to do scanf for single char in C

Benjamin J.
  • 1,152
  • 1
  • 15
  • 24
0

It would be correctly to write

printf("What is your name?: ");
scanf("%s", n);
           ^^^

or even

printf("What is your name?: ");
scanf("%9s", n);

instead of

printf("What is your name?: ");
scanf("%s", &n);

and

printf("Are you male or female?: ");
scanf(" %c", &s);
      ^^^

instead of

printf("Are you male or female?: ");
scanf("%c", &s);

Otherwise in the last case a white space character is read into the variable s.

Vlad from Moscow
  • 265,791
  • 20
  • 170
  • 303