Varian
Varian

Reputation: 11

else-if only giving out the if answer

I'm working on a project for my computer science class. We have to make a text adventure game. I've gotten almost all of it to work except for the loop at the end. The if statement works fine, but the else if statement only puts out the answer to the if statement, not the separate statement I wrote for it. I've tried many different ways of writing this, but I honestly can't see the problem. I'll include the whole code in case there is a problem somewhere outside of the loop.

#include <stdio.h>
int main() {
    char name[1024];
    char kname[1024];
    char response[1024];
    printf("Wanna play a game? First, I need your name.\n");
    scanf("%s", name);
    printf("Your name is %s, huh? I like it.\n", name);
    printf("Let's get started. You're in the woods. You come across a cat, now you need to name them.\n");
    scanf("%s", kname);
    printf("So, you decided to name them %s? Not what I would've picked, but it's not my pet.\n", kname);
    printf("You come across a plague doctor. Is that why you came into the woods, to get away from the sickness? Not exactly brave. Anyway, I digress. The plague doctor promises the impossible, tells you that he can and will make you immune with an elixir. Do you take it?\n");
    scanf("%s", response);
    if (response, "yes") {
        printf("You took it, huh? Not what I would've picked, but hey, you seem fine. Uh oh, you don't look so good. I...don't think that was a good idea. Well, there's nothing I can do for you now. Maybe restart the game and see if you can make a better decision. Until next time, old friend.");
    } else if (response, "no") {
        printf("Good choice. Come on, I think there's a town up ahead. I'd list off what the town's name was and all that can be found there, but it's currently 11:32 pm on a Saturday and our creator is halfway convinced that this entire program is a fever dream.");
    }
    return 0;
}

Upvotes: 1

Views: 377

Answers (1)

if (response, "yes") and else if (response, "no") do not have appropriate condition tests for the thing want you want to do with it - comparing two strings and control the flow by the result whether there are equivalent or not.

(response, "yes") get evaluated to 1 where the if statement´s condition will always become true. Thus, the else if-statement or statements (if there are multiple) thereafter will never get executed.

Use strcmp() to compare two strings with each other.

Change if (response, "yes") to if (!strcmp(response,"yes")) and else if (response, "no") to if else (!strcmp(response,"no")) and everything should be fine.

Don´t forget to include the header of string.h by #include <string.h> to use strcmp().

Upvotes: 1

Related Questions