Taicho hasegawa
Taicho hasegawa

Reputation: 19

C programming how do i use if statement properly with strings for the below code?

#include <stdio.h>

int main()
{

    char apple[]="Apple";
    char banana[]="Banana";
    char orange[]="Orange";

    printf("Choose one of the below options\n\n");
    printf("Which fruit do you like the most: Apple, Banana, Orange\n\n");
    scanf("%s",&apple,&banana,&orange);
    if("%s", apple)
    {
        printf("You chose Apple.\n");
    }
    if("%s",banana)
    {
        printf("You chose banana.\n");
    }
}

// I want the code to simply print on screen the choice i chose. But when i run the code it prints both Apple and Banana. If i type Apple i do not want it to print Banana. Do i need to use else statement with this? or what else am i missing? Thank you i am very new to c programming.

Upvotes: 0

Views: 216

Answers (1)

MD. Khairul Basar
MD. Khairul Basar

Reputation: 5110

You need to use strcmp() to compare between strings. see the following code.

strcmp() will return 0 if the contents of both strings are equal.

strcmp() will return <0 if the first character that does not match has a lower value in ptr1 than in ptr2.

strcmp() will return >0 if the first character that does not match has a greater value in ptr1 than in ptr2.

reference

#include <stdio.h>
#include <string.h>

int main()
{

    char apple[]="Apple";
    char banana[]="Banana";
    char orange[]="Orange";
    char input[100];

    printf("Choose one of the below options\n\n");
    printf("Which fruit do you like the most: Apple, Banana, Orange\n\n");
    scanf("%s",input);
    if(strcmp(input,apple)==0)
    {
        printf("You chose Apple.\n");
    }
    if(strcmp(input,banana)==0)
    {
        printf("You chose banana.\n");
    }
    if(strcmp(input,orange)==0)
    {
        printf("You chose orange.\n");
    }
    return 0;
}

Upvotes: 1

Related Questions