c - 在数组中添加项目

标签 c

当我尝试向数组添加元素时遇到问题,并且总是itemID 已存在 我尝试解决它,但无法解决 这是我的功能

int AddNewItem(){
    FILE* f = fopen("items.txt", "a");
        if(f == 0) {
                printf("file is not present :\n");
                return 0;
        }
        int ItemID,ItemQuantity,PricePerUnit, i = 0,flag = 0;
        int ItemI[10], ItemQ[10],Price[10];

        while(fscanf(f,"%d%d%d",&ItemI[i],&ItemQ[i],&Price[i])>0){
                ++i;
        }
        printf("Enter itemID: ");
        scanf("%d",&ItemID);
        for(i=0; i<10; i++)
        {
                if(ItemI[i]==ItemID)
                {
                        flag = 1;
                        printf("the itemID already exists\n");
                        break;
                }
                else{
                    ItemI[i+1]=ItemID;

                }
            }

        printf("Enter The price per unit ");
        scanf("%d",&Price[i]);

        fclose(f);
        return ;
}

谢谢 这是我的文件

1007 5 30

1004 4 10

1003 3 20

1002 2 10

1006 4 40

1005 5 50

1001 1 70

1008 6 20

1010 4 90

1009 3 10

最佳答案

那是因为:

            if(ItemI[i]==ItemID)

假设该陈述在第一次迭代时为假。 'else' 将被执行:

            else {
                ItemI[i+1]=ItemID;
            }

因此 ItemI[1] 被设置为 ItemID。在下一次迭代中,当“i”等于 1 时,“if”语句始终为 true。这就是为什么它打印“itemID 已存在”

关于c - 在数组中添加项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47743942/

相关文章:

c - 在数组中使用 int 还是 char?

c编程链表段错误

c - 以固定大小的位数组作为键查找表

c - 在 C 中使用头文件

c - 指向结构 C 指针的指针

c - C 新手,类似二十一点的程序的错误消息问题

c - 调用 clock_gettime() 时,返回的 tv_nsec 字段实际上可能超过一秒吗?

c - 从函数中获取随机字符

c - 写入视频内存(0xB8000)和 volatile 指针

c - 如何从文件中获取字符串并存储在二维字符数组中,并将该二维字符数组与 C 中的字符串进行比较?