Whats wrong?

+1 Jovin Yeap · April 7, 2015
char answer;

    printf("Do you like donuts? (Yes/No) \n");
    scanf(" %s", answer);

    if(  (answer=="Yes") || (answer=="No")  ) {
        printf("Thanks for answering the survey \n");
    }else{
        printf("Dude, answer yes or no \n");
    }


Hey guys. This is a mini learning script i came up with. The problem is when I type in Yes or No it says "Dude, answer yes or no" instead of "Thanks for answering the survey". Can anyone tell me what did I do wrong?

Post a Reply

Replies

Oldest  Newest  Rating
0 Dol Lod · April 7, 2015
How does this even compile? Seriously ...

First, what you scan into should actually be a character array, not an individual character.

Second,you can't directly check string values like that. You need to look up string.h for C and use their string comparison function or make your own. 
0 Yaron X · April 8, 2015
1. answer is defined as a 1 char only field. it should be an array, e.g.:
 char answer[50];

2. The scanf is likely to crash your program sometimes, because it expects you to pass a pointer which will receive the %s . answer is not a pointer - it's just a char. The compiler is going to cast whatever value is in "answer" to a pointer value and when the user enters a string and press OK, the entered string will be copied to that address and cause an access violation error.

If anything, the line should have been:
scanf(" %s", &answer); // ampersand before answer

but once you change the definition of answer to an array (as shown above)  then it can stay as it is.
scanf(" %s", answer);

3. the way you wrote the compare line, the program is comparing pointers, not the actual values of the strings.
you should use strcmp or stricmp

if( ( stricmp(answer,"Yes")==0 ...
0 Islam Kamilov · April 7, 2015
Try with this one:

 char answer:

printf("Do you like donuts? (Yes/No) \n");
scanf(" %c", answer);

if( (answer=='Yes') || (answer=='No') ) {
printf("Thanks for answering the survey \n");
}else{
printf("Dude, answer yes or no \n");
}

I hope it would helpful to you :)
  • 1

C

107,148 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator