Learner_15
Learner_15

Reputation: 399

If char was only to be used with an if statement, how can it be used with an %c or %s?

The problem I'm getting at is with this following code.

Basically, I'm confused since I know that char should be matched with %c.

Yet, I also know that %c gets only one character, which means that in order to get the word in the if statement ('man' or 'woman'), it has to become a %s.

But then, %s doesn't match with char.

I would like to ask: if I were to leave char as it is, what would be the problem with my idea and code that is making the result unable to come out properly?

int main() {
    char gender;

    printf("Enter gender(M/F) : ");
    scanf("%c", &gender);
    if (scanf("%c", &gender) == 'M') {
        printf("Man");
    }
    else if (scanf("%c", &gender) == 'F') {
        printf("Woman");
    }

    printf("The gender is %c.", gender);

    return 0;
}

Upvotes: 0

Views: 328

Answers (1)

Feronimus
Feronimus

Reputation: 123

Why don't you use the getchar() instead?

int main()
        {

            printf("Enter gender(M/F) : ");
            char gender = getchar();

            if (gender == 'M')
                printf("Man\n")

            if (gender == 'W')
                printf("Woman\n")

            printf("The gender is %c.\n", gender);

            return 0;
        }

Also its a good practice to enclosure your reading into a while loop and break from it only if the char that you got from the user is acceptable (Check for EOF or any other char , show an error message and try again.)

Alternative just use scan only one time:

  int main()
        {

            printf("Enter gender(M/F) : ");
            char gender;
            scanf(" %c", &gender);

            if (gender == 'M')
                printf("Man\n")

            if (gender == 'W')
                printf("Woman\n")

            printf("The gender is %c.\n", gender);

            return 0;
        }

Upvotes: 2

Related Questions