Nopiforyou
Nopiforyou

Reputation: 350

C - if/else statement

I'm fairly competent with if/else statements, and this is a really old assignment that I ended up turning in partially complete. But I still wanted to know exactly why my code wouldn't work.

I want my user to input name, height, and sex. My code will then display an entire sentence that says "Name is X cm tall and is a male" or "Name is X cm tall and is a female."

When I input name and enter, it immediately then skips displays both the height AND the sex. Regardless of what I input after that, it then ends the program.

Input name: Jack Input height in cm: 180 sex(M/F): Computer $

I've been playing around with this code for a while now, but I have been stuck for a while now. Any help would be greatly appreciated. Here is my code:

#include<stdio.h>

int main() {
  char name[30];
  char sex;
  float height; 

  printf("Input name: ");
  scanf("%s", name);
  fflush(stdin);
  printf("Input height in cm: ");
  scanf("%f", &height);
  fflush(stdin);

  printf("sex(M/F): ");
  scanf("%c", &sex);
  if (sex == 'M') 
  {
    printf("%s is %f cm tall and male", name, height);
  }
  else if (sex == 'F')
  {
    printf("%s is %f cm tall and female", name, height);
  }
  printf("\n");
  return 0;
}

Upvotes: 1

Views: 3535

Answers (5)

DevN
DevN

Reputation: 325

To read a single character from stdin you have to use getchar() instead of scanf("%c", &c) Or change the variable type of sex to char[2] and use scanf("%s", sex)

Upvotes: 0

rakeshNS
rakeshNS

Reputation: 4257

You can also try this

printf("sex(M/F): ");
scanf("%s", &sex);

Upvotes: 0

Thomas Frei
Thomas Frei

Reputation: 141

You're missing an ampersand on line 9:

scanf("%s", name);

shoul be:

scanf("%s", &name);

maybe this helps

Upvotes: 0

md5
md5

Reputation: 23699

fflush(stdin) is a very bad idea (undefined behavior). You should replace this call with an other function call, for example this one :

static void
clean_stdin(void)
{
    int c;
    do {
        c = getchar();
    } while (c != '\n' && c != EOF);
}

With it, it seems working.

Upvotes: 0

cnicutar
cnicutar

Reputation: 182609

From what I can see it only skips the sex part - which is very sad to be honest :-)).

it immediately then skips displays both the height AND the sex

Input name: Jack Input height in cm: 180 sex(M/F): Computer $

You can try this:

scanf(" %c", &sex);
       ^

The space causes scanf to eat blanks before reading a character.

Upvotes: 5

Related Questions