0

I can't seem to figure out what's wrong with this. It compiles fine, but no matter what I put in, be it yes or no, it skips over the "let's begin" line and goes straight to the end.

#include<stdio.h>
#include<stdlib.h>

int main(){
    char response[5];
    printf("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");
    printf("Would you like to go on an adventure?\n Enter Yes or No:");
    scanf("%s", response);
    if (response == "yes"){
        printf("Let's begin!");
    }
    else (response == "no");{
        printf("See you later then!");
    }
    return 0;
}

Does the scan need to be moved, or did I just screw it up somehow?

jeff carey
  • 2,313
  • 3
  • 13
  • 17
hego64
  • 345
  • 1
  • 5
  • 17
  • The `==` does not compare arrays. If use on arrays it compares the addresses of the two array's 1st element. – alk Jan 28 '17 at 08:14

4 Answers4

1

Change

if (response == "yes"){

to

if(!strcmp(response, "yes") {

For the "no" check, write else if(!strcmp(response, "no") { if you want to explicitly check for "no".

jeff carey
  • 2,313
  • 3
  • 13
  • 17
  • 1
    And the OP should remove the `(response == "no")` in the else. – lurker Jan 27 '17 at 21:16
  • Thanks for catching that, I've updated my answer. – jeff carey Jan 27 '17 at 21:21
  • Hey, that fixed it! Thanks a ton; I had no clue that I couldn't use == for chars. – hego64 Jan 27 '17 at 21:23
  • @hego64 you can use `==` for characters. But you were trying to compare two different addresses. `response` is the address of the response. `"yes"` is the address of the string `"yes"` in memory. So `response == "yes"` compares memory addresses of two different arrays of characters. – lurker Jan 27 '17 at 21:34
0

You are comparing array of chars. So == will not work. Either implement equals function for 2 array of chars or use string class.

cuongptnk
  • 472
  • 3
  • 15
0
if (strcmp(response, "yes")==0){
    printf("Let's begin!");
}
else {
    printf("See you later then!");
}

You cannot compare two char arrays. 0 is returned from strcmp when the strings are the same. Make sure to include .

0

in c programming you can't directly compare array of characters by using assignment operator instead you can use strcmp to check both the string are equal or not

mrsk
  • 55
  • 1
  • 8