基本食物银行计划需要帮助

时间:2014-10-08 23:48:10

标签: c string multidimensional-array

我在下面的代码中遇到选项2的问题,即请求。每次我打印出请求表,而不是显示用户输入的待处理请求,它给我一个随机的高数字。有人可以帮我找到问题吗?代码应该与选项1类似,但如果用户输入相同,则它不应该添加用户输入。示例输出:

1
Milk 20
1
Milk 20
2
Milk 10
2
Milk 5
4
Donations: 
Milk 40
Requests: 
Milk 10
Milk 5

这是我的代码

int main() {

int don_count=0, don_amt[100], found, i, don_quant, option, req_count=0, req_amt[100],req_quant;

char word[20], don_inv_type[100][20], req_word[20], req_inv_type[100][20];

printf("Welcome to the food bank program!);
printf("1.Enter a Donation\n2.Enter a Request\n3.Fulfill the earliest Request\n4.Print status report\n5.Exit\n");
scanf("%d", &option);

while (option != 5) {

      // Execute a deposit.
      if (option == 1) {
                 scanf ("%s", word);
                 scanf ("%d", &don_quant);
                 found = -99;
                 for (i=0;i<don_count; i++){
                     if (strcmp(don_inv_type[i], word)==0)
                     found = i;
                     }
                 if (found == -99){
                               strcpy(don_inv_type[i],word);
                               don_amt[i] = don_quant;
                               don_count ++;
                               }
                 else
                         don_amt[found] += don_quant;
      }

      else if (option == 2) {
           scanf ("%s", req_word);
           scanf ("%d", &req_quant);
           req_count++;
           for(i=0; i<req_count; i++)
           {
                    strcpy(req_inv_type[i],req_word);
                    req_amt[i] += req_quant;
           }
      }

      else if (option == 3) {


      }

      else if (option == 4) {
           printf("Donations:\n");
           for(i=0;i<don_count;i++){
                                    printf("%8s", don_inv_type[i]);
                                    printf("%5d\n", don_amt[i]);
                                    }
           printf("Requests: \n");
           for(i=0;i<req_count;i++){
                                    printf("%8s", req_inv_type[i]);
                                    printf("%5d\n", req_amt[i]);
                                    }


      }

      else if (option == 5) {
           printf(" Thanks bye");     

      }

      // Reprompt the menu.
      printf("1.Enter a Donation\n2.Enter a Request\n3.Fulfill the earliest Request\n4.Print status report\n5.Exit\n\n");
      scanf("%d", &option);
} // end while

system("PAUSE");
return 0;
} // end main

1 个答案:

答案 0 :(得分:0)

您永远不会初始化req_amt,因此req_amt[i] += req_quant只是将req_quant添加到之前在这些内存位置的垃圾。

您需要执行以下操作:

int req_amt[100] = {0};
                ^^^^^^  <--- Add this

或以其他方式手动初始化元素。