C問題

本帖最後由 kyoiori 於 2010-5-8 01:22 編輯

我弄了很久, 我用struct, 也用過typedef, 但不知道為什麼, 也是不能正確顯示結果
請問用了struct不是可以直接用newb = b2;嗎?

Why you don't write your code here?

int main(void)
{
  struct brands {  char bdname[10];
                   int store;
                };
  struct brands b1 = {"brand1",240};
  struct brands b2 = {"brand2",326};
  struct brands b3 = {"brand3",139};
  struct brands newb;
  char input[5]={'\0'};
  
  printf("Input the product brand : ");
  scanf("%s",&input);

if (input == "brand1")
      newb = b1;
if (input == "brand2")
      newb = b2;
if (input == "brand3")
      newb = b3;
      
printf("\nThe information of %s\nStock: %d\n",input,newb.store);
  
  system("PAUSE");
  return 0;
}

Your problem is the following lines of code:
char input[5]={'\0'};

1. 5 characters is too short for your input, your intended data 'brand1' is 7 characters (6 characters + '\0') already.

if (input == "brand1")
      newb = b1;

1. You cannot compare string by "==" operator, use strcmp() etc.
2. newb is a complex type (a struct variable) as well as b1, and they cannot be copied this way.  Maybe you want to use pointer, something like "struct brands *newb;" etc.
      
Stephen Wong @ Hong Kong

TOP

原來要用strcmp() , 感謝

TOP

if (strcmp(input,b1.bdname)==0);
    newb = b1;
if (strcmp(input,b2.bdname)==0);
    newb = b2;
if (strcmp(input,b3.bdname)==0);
    newb = b3;
怪了,我改了上面這樣之後可以正常顯示,但是如果我輸入brand1,輸出的是brand3的數值,為什麼呢?

還有是如果用struct brands *newb;
在printf時用*newb.store或newb.store都會顯示錯誤

TOP

if you really need to copy a complex (struct) variable, you need something like:

memcpy(&newb, &b1, sizeof (struct brands));

However, as I said, you might not want to copy the structure, but only to use a pointer to point to your 'answer'.  In your code, I don't know what you want to do further with your newb, but think about in a more complex situation, you might want to change the name of your brands (ie. change 'brand1' to 'brandx'), if you copy the structure, you will not have the 'new' changed brandname in newb.  Anyway, it's more a data analysis issue, and might be too difficult for you at the moment.

If you use a pointer, you use ptr->component to reference, instead of ptr.component.

Stephen Wong @ Hong Kong

TOP

本帖最後由 kyoiori 於 2010-5-8 13:10 編輯

謝謝,
我不明白的是strcmp比較input與b1.bdname之後是出0,而input與b3.bdname是出1, 但係結果仍會變為brand3(即最後一個)的內容,即似乎仍會執行newb = b3;
如果我將
if (strcmp(input,b1.bdname)==0);
    newb = b1;
放在最後,那當我輸入"brand1"時才可以出到正確的b1.store, 這是什麼回事呢

TOP

Hey, NO semicolon at the end of if statement!!!

if (strcmp(input,b1.bdname)==0);
    newb = b1;
if (strcmp(input,b2.bdname)==0);
    newb = b2;
if (strcmp(input,b3.bdname)==0);
    newb = b3;

Stephen Wong @ Hong Kong

TOP

哈哈, 多謝提醒, 我都沒發覺

TOP