siannone
siannone

Reputation: 6763

If condition not being respected

i'm having a problem with the following code:

/* 
 * Esercizio 5
 */

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

char* getProduct(char product[]);
long getNumber(char product[]);

int main(int argc, char** argv) {

    char product1[60] = {0};
    char product2[60] = {0};
    char product3[60] = {0};
    char productInput[60] = {0};

    int flag = 0;
    long cost = 0;

    printf("Product 1: ");
    gets(product1);
    printf("Product 2: ");
    gets(product2);
    printf("Product 3: ");
    gets(product3);

    do {

        printf("Product and quantity: ");
        gets(productInput);
        printf("productInput: %s\n", getProduct(productInput));
        printf("product1: %s\n", getProduct(product1));
        if(getProduct(product1) == getProduct(productInput)){ /* PROBLEM HERE!!! */

            // No matter what i input it always goes here
            printf("Selezionato prodotto 1");
            cost = getNumber(product1) * getNumber(productInput);
            flag = 1;

        } else if(getProduct(product2) == getProduct(productInput)){

            printf("Selezionato prodotto 1");
            cost = getNumber(product2) * getNumber(productInput);
            flag = 1;

        } else if(getProduct(product3) == getProduct(productInput)){

            printf("Selezionato prodotto 1");
            cost = getNumber(product3) * getNumber(productInput);
            flag = 1;

        }

    }  while(!flag);

    printf("Costo totale: %d", cost);

    return (EXIT_SUCCESS);
}

char* getProduct(char product[]){

    char *pointer;
    char str_product[60] = {0};

    strcpy(str_product, product);

    pointer = strtok(str_product, " ");

    return pointer;

}

long getNumber(char product[]){

    char *pointer;
    char str_product[60] = {0};

    strcpy(str_product, product);

    pointer = strtok(str_product, " ");
    pointer = strtok(NULL, " ");

    return strtol(pointer, NULL, 10);

}

As you can clearly see, getProduct(productInput) and getProduct(product1) return pointers to different values. The problem is that even if values are different the if condition is not being respected.

Upvotes: 1

Views: 130

Answers (1)

Attila
Attila

Reputation: 28782

You are trying to compare strings by the == operator, which is not doing what you expect it to do.

Instead you need to compare them by calling strcmp() (or better yet, strncmp())

if(strmcp(getProduct(product1), getProduct(productInput)) == 0){ 

The reason why comparing strings by == does not work properly is that == compares the pointers (basically, the memory location where the strings are stored), not the strings themselves

Upvotes: 6

Related Questions