Search code examples
cif-statementcomparisonc-stringsstring-literals

Code is not working, and is not doing directed task


The code is self explanatory, but I need help because, when I use it, it skips all the "If" cases and jumps to the next loop directly. The "scanf" works correctly; the variable "order" receives input correctly too. If you figure out how to fix it, Let me know! Have a great day!

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

int main(){
    int side [3]; // Fries(0), Fried Squid(1), Cheese Fries(2)
    int combo [3]; // Spicy Chicken(0), Whopper(1), Double Whopper(2)
    int drinks[3]; // Cola(0), Vanilla Shake(1), Lemonade(2)
    int amount;
    char order [20];
    int total = 0;

    for(int i = 0; i < 3; ++i){
        combo[i] = 20;
        total = total + 20;
    }
     for(int i = 0; i < 3; ++i){
        side[i] = 20;
        total = total + 20;
    }
    for(int i = 0; i < 3; ++i){
        drinks[i] = 20;
        total = total + 20;
    }

    while (total > 0){
        printf("Make your order here: \n");
        scanf("%s %d", order, &amount);
        printf("%s\n", order);
        if(order == "Fries"){
            printf("A\n");A
            if(side[0] < amount){
                printf("Your order is invalid, and you are stinky.\n");
            }
            else{
                printf("B\n");
                printf("your order is here: %s x %d", order, amount);
                total = total - amount;
            }
            printf("C\n");
        }
        printf("D\n");
    }
    return 0;
}




Solution

  • The condition in if statements like this

    if(order == "Fries"){
    

    does not make a sense. There are compared two pointers and it is evident that they have different values. That is the character array order is implicitly converted to pointer to its first element and the string literal is also implicitly converted to a pointer the same way.

    Pay attention to that if you will even write for example

    if("Fries" == "Fries"){
    

    then it is not necessary that the expression will evaluate to the logical true. The result of the expression depends on a compiler option that is whether the compiler stores identical string literals as one string literal or as different string literals.

    What you need is to compare two strings like

    #include <string.h>
    
    // ...
    
    if( strcmp( order, "Fries" ) == 0 ){