我对以下代码有疑问:
/*
* 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);
}
如您所见,getProduct(productInput)
并getProduct(product1)
返回指向不同值的指针。问题是,即使值不同,if
条件也没有得到尊重。