Help?

+1 Julia L · November 6, 2015
I'm trying to get this code to work, but I don't know what's wrong with it. Please help!

it's not showing up here in this post, but the two includes are:

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


int main(){

char userName[20];
char popcornAnswer[20];

printf ("What is your name? \n\a");
scanf ("%s", userName);

printf ("Do you like popcorn? (y/n) \n\a");
scanf ("%s", popcornAnswer);

if (popcornAnswer == 'yes'){
    printf ("You eat a lot \n\a");
}

else if (popcornAnswer == 'no'){
    printf ("What's wrong with you? \n\a");
}
    else{
    printf("what\n\a");
}

   return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
0 c student · November 6, 2015
look up the string.h header
0 Jeff T. · November 6, 2015
When comparing strings in c you can't use the == because it compares the addresses of the two strings not the individual characters, that's why your program keeps going to the default 'what' statement. If you want a quick workaround change your popcornAnswer array  to a char variable only, add the '&' symbol to the scanf() and change the 'yes'/'no' in the 'if' statements to 'y'/'n'. This will get your program working, using 'y'/'n' is the answer your asking for in your question anyway. Just remember when programming be VERY clear on what your expected input should be when asking questions, otherwise as humans we will surely find a way to screw it up :)!!!!
The other way to get it going is like c student said, look up the functions in the string.h header, that file gives you the functions your looking for and is the correct way of comparing strings in c.
Good Luck!!
0 Akshay Narula · November 6, 2015
use "yes"  In Double Quotes

reason is you choose %s
and %s is used for string
"and string always in double quotes"
0 neeraj polas · November 14, 2015
use header #include <string.h>

and to compare two string you should use 
strcmp(string1, string2);
if string1 > string2 it returns -1
if string 1 < string 2 it returns 1
if equal it returns 0

here, I've modified your program

#include
#include
#include
int main()
{
    char userName[20];
    char popcornAnswer[20];

    printf ("What is your name? \n\a");
    scanf ("%s", userName);

    printf ("Do you like popcorn? (y/n) \n\a");
    scanf ("%s", popcornAnswer);

        if (strcmp(popcornAnswer,"yes"))
        {
            if (strcmp(popcornAnswer,"no"))
                printf ("What?\n");
                else
                printf ("What's wrong with you?\n");
        }
        else
            printf ("You eat a lot!");
return 0;
}
0 Julia L · November 21, 2015
really sorry for the late reply... but thank you to everybody !!
  • 1

C

107,295 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator