【发布时间】:2017-03-05 04:44:50
【问题描述】:
我是 C 的初学者,但我在使用结构时遇到了问题。 在我向用户询问所有属性之后,我想打印结构的所有值。问题是,在我将所有属性输入到一个结构并再次循环返回第二次请求属性后,第一个结构输入被第二个结构输入替换。 我很确定我一遍又一遍地分配相同的内存空间,从而导致问题,但我坚持如何解决它。我很感激任何关于我能做什么的建议。谢谢!
case 2:
printf ("Please input a SKU number:");
scanf ("%d", &item[MAX_ITEMS].sku_);
printf ("Quantity:");
scanf ("%d", &item[MAX_ITEMS].quantity_);
printf ("Price:");
scanf ("%f", &item[MAX_ITEMS].price_);
printf ("The item is successfully added to the inventory");
break;
打印出sku、数量和价格
switch (menuSelection) {
case 1:
printf ("Inventory\n");
printf ("=========================================\n");
printf ("Sku Price Quantity\n");
for (i =0 ; i<=MAX_ITEMS; i++){
printf ("%d %.2f %d\n", item[i].sku_, item[i].price_, item[i].quantity_);
}
printf ("=========================================\n");
break;
这是我的全部代码:
#include <stdio.h>
#define MAX_ITEMS 10
struct Item{
int sku_;
float price_;
int quantity_;
}item[MAX_ITEMS];
int main (void) {
int size=0;
int menuSelection;
int i=0;
printf ("Welcome to the Shop\n");
printf ("===================");
do {
printf ("\nPlease Select from the following options:\n");
printf ("1) Display the inventory.\n");
printf ("2) Add to shop.\n");
printf ("0) Exit.\n");
printf ("select:");
scanf ("%d", &menuSelection);
if (menuSelection <0 && menuSelection >2){
printf ("Invalid input, try again: Please select from the following options:");
}
else {
switch (menuSelection) {
case 1:
printf ("Inventory\n");
printf ("=========================================\n");
printf ("Sku Price Quantity\n");
for (i =0 ; i<=MAX_ITEMS; i++){
printf ("%d %.2f %d\n", item[i].sku_, item[i].price_, item[i].quantity_);
}
printf ("=========================================\n");
break;
case 2:
printf ("Please input a SKU number:");
scanf ("%d", &item[size].sku_);
printf ("Quantity:");
scanf ("%d", &item[size].quantity_);
printf ("Price:");
scanf ("%f", &item[size].price_);
printf ("The item is successfully added to the inventory");
break;
case 3:
break;
}
}
} while (menuSelection != 0);
return 0;
}
【问题讨论】:
标签: c arrays loops struct dynamic-memory-allocation