1

我对以下代码有疑问:

/* 
 * 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条件也没有得到尊重。

4

1 回答 1

6

您正在尝试通过==运算符比较字符串,这并没有按照您的预期进行。

相反,您需要通过调用strcmp()(或者更好的是,strncmp())来比较它们

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

比较字符串==不能正常工作的原因是==比较指针(基本上是存储字符串的内存位置),而不是字符串本身

于 2012-05-27T18:36:18.047 回答