我遇到以下代码的问题:
/*
* 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
条件。
答案 0 :(得分:6)
您正试图通过==
运算符比较字符串,这不符合您的预期。
相反,您需要通过调用strcmp()
(或者更好,strncmp()
)来比较它们
if(strmcp(getProduct(product1), getProduct(productInput)) == 0){
==
比较字符串不正常的原因是==
比较指针(基本上是存储字符串的内存位置),而不是字符串本身