【问题标题】:Structure C: Storing values in an array结构 C:将值存储在数组中
【发布时间】:2016-11-20 03:08:53
【问题描述】:

谁能告诉我为什么值没有存储在结构数组中? 我试图将值存储在缓冲区数组中,我注意到存储的值是 0 或 1 而不是用户输入。

这是我尝试过的:

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int menu(void);
struct item
{
    int i_SKU;
    int i_QUANTITY;
    int i_PRICE;
};

int main()
{
    int i,j = 0;;
    int n;
    int input;
    //struct item item1[10] = { {0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0} };
    struct item item1[]={0};
    struct item buff[]={0};
    //printf("size of %d", sizeof(item1)/sizeof(item1[0]));
    printf("Welcome to the Inventory\n");
    printf("===================\n");
B: printf("Please select from the following:\n");

A: menu();
    scanf("%d", &input);

    switch (input)
    {
        case 1:
            printf("Inventory\n");
            printf("=========================================\n");
            printf("ku     Price     Quant\n");
            for (i = 0; i < sizeof(buff)/sizeof(buff[0]); i++)
            {
                printf("%d     %d        %d\n", buff[i].i_SKU, buff[i].i_PRICE, buff[i].i_QUANTITY);
            }
            printf("=========================================\n");
            goto B;

        case 2:
            //n = sizeof(item1)/sizeof(item1[0]) + 1;
            //for (i=n; i < ; i++)
            printf("Please input a KU number:");
            buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
            printf("Quantity:");
            buff[j].i_QUANTITY=scanf("%d", &item1[j].i_QUANTITY);
            printf("Price:");
            buff[j].i_PRICE=scanf("%d", &item1[j].i_PRICE);
            printf("The item added.\n");
            j=j+1;
            goto B;

        case 0:
            printf("bye!");
            exit(1);

        default:
            printf("Invalid input, try again:\n");
            goto A;
    }

    return 0;
}

int menu(void)
{
    printf("1) Display.\n");
    printf("2) Add to inventory.\n");
    printf("0) Leave.\n");
    printf("Select:");
    return 0;
}

我尝试将值存储在缓冲区数组中,但我注意到存储的值是 0 或 1 而不是用户输入。

【问题讨论】:

标签: c arrays struct structure


【解决方案1】:

scanf 不返回它读取的值,它返回它读取的字符数。

所以这些行:

buff[j].i_SKU=scanf("%d", &item1[j].i_SKU);
buff[j].i_SKU=scanf("%d", &item1[j].i_QUANTITY);
buff[j].i_SKU=scanf("%d", &item1[j].i_PRICE);

不要做你想做的事。他们将整数放入item1[j].i_X,但将buff[j].i_X 分配给读取的字符数。

另外,我猜你是想让这三个等式的左边有所不同,而不是全部引用 i_SKU

另一个可能的问题:您的缓冲区没有指定长度,因此它们可能只有一个元素的存储空间。

编辑

我不确定items1 数组在您的代码中的用途,但如果您想要两个数组中的值,您可以尝试以下操作:

int sku;
printf("Please input a KU number:");
buff[j].i_SKU=scanf("%d", &sku);
item1[j].i_SKU = sku;
buff[j].i_SKU = sku;
// etc.

【讨论】:

  • 否则我如何存储值?
  • 您用于将值存储在item1[j].i_X 中的方法应该可以工作。
  • 值仍然没有存储在 buff 中
  • 如果您更新问题中的代码,我可以看看。
猜你喜欢
  • 2014-06-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-06-19
  • 1970-01-01
  • 2011-09-27
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多