2 Replies - 346 Views - Last Post: 24 August 2019 - 10:54 AM Rate Topic: -----

#1 Caedmon   User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 10
  • Joined: 23-August 19

I am having trouble in testing a character in if statement.

Posted 24 August 2019 - 10:47 AM

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char gender[1];
printf("What is your gender(m/f)?");
scanf("% c",gender);
if(gender == 'm'){
printf("Hello Sir");
}else {
printf("Hello Madam");
}
return 0;
}


In this code,even if I enter 'm' character, the computer displays Hello Madam. It is as if the computer is having some trouble in testing the character in if statement.

Is This A Good Question/Topic? 0
  • +

Replies To: I am having trouble in testing a character in if statement.

#2 jimblumberg   User is offline

  • member icon

Reputation: 5745
  • View blog
  • Posts: 17,601
  • Joined: 25-December 09

Re: I am having trouble in testing a character in if statement.

Posted 24 August 2019 - 10:53 AM

Could it be that you defined gender as an array of char instead of just a single char and that you are trying to compare that array to a single char?

Jim
Was This Post Helpful? 0
  • +
  • -

#3 Salem_c   User is offline

  • void main'ers are DOOMED
  • member icon

Reputation: 2369
  • View blog
  • Posts: 4,496
  • Joined: 30-May 10

Re: I am having trouble in testing a character in if statement.

Posted 24 August 2019 - 10:54 AM

> scanf("% c",gender);
You need to be careful and specific with your formats.
"% c" != " %c"

Also, you're comparing an array with a character.

Compile with lots of warnings, and fix them before running code.
$ gcc -Wall -Wextra foo.c
foo.c: In function ‘main’:
foo.c:7:7: warning: unknown conversion type character 0x20 in format [-Wformat=]
 scanf("% c",gender);
       ^
foo.c:7:7: warning: too many arguments for format [-Wformat-extra-args]
foo.c:8:11: warning: comparison between pointer and integer
 if(gender == 'm'){
           ^



See
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
  char gender[1];
  printf("What is your gender(m/f)?");
  scanf(" %c", gender);
  if (gender[0] == 'm') {
    printf("Hello Sir");
  } else {
    printf("Hello Madam");
  }
  return 0;
}



Also, practice your indentation.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1