c - 关于数组搜索

标签 c

...................................................... ...................................................... ...................................................... ………… 大家好,当我在数组中搜索元素时,我遇到了一个小问题 当我输入 1007 这样的数字时,他总是给我错误:无效的项目 ID

这是我的文件

1007 5 30

1004 4 10

1003 3 20

这就是我的职责

<小时/>
void DisplayItemInfoForAParticularItem(){
    FILE* f = fopen("items.txt", "r");
    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]) != EOF){
        ++i;
    }
    printf("Enter itemID: ");
    scanf("%d",&ItemID);
    for(i=0; i<10; i++)
    {

        if(ItemI[i]==ItemID)
        {
            flag = 1;
            printf("ItemID  Quantity    Price Per Unit (SAR)");
            printf("%d  %d  %d",ItemI[i],ItemQ[i],Price[i]);
            break;
        }
    }
    if(flag==0)
    {
         printf("Error: Invalid item ID");
    }

    fclose(f);
   return ;
}

感谢您的帮助...................................... ...................................................... ...................................................... ...................................................... ...................................................... ...................................................... ........

最佳答案

fscanf() 类似于 scanf(),您尝试从 文件扫描,而不是从 用户 扫描 但扫描后你存储在哪里? ItemI[i] 应该是 &ItemI[i] 不是吗?

 while(fscanf(f,"%d%d%d",&ItemI[i],&ItemQ[i],&Price[i])>0){
                ++i;

编辑:我认为您希望以一种方式输出,但您以不同的方式编写,所以我编辑了您的代码。

int DisplayItemInfoForAParticularItem(){
        FILE* f = fopen("items.txt", "r");
        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;
        }

        for(i=0; i<10; i++)
        {
                printf("Enter itemID: ");
                scanf("%d",&ItemID);
                if(ItemI[i]==ItemID)
                {
                        flag = 1;
                        printf("ItemID  Quantity    Price Per Unit (SAR)\n");
                        printf("%d  %d  %d\n",ItemI[i],ItemQ[i],Price[i]);
                        break;
                }
                if(flag==0)
                {
                        printf("Error: Invalid item ID");
                }
        }
        fclose(f);
        return ;
}

希望对您有所帮助。

关于c - 关于数组搜索,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47728253/

相关文章:

c - 使用 DFS 查找迷宫中的所有路径

c - 获取 C 程序修改的所有内存位置的日志

c - c语言中vprintf线程安全吗?

c - Dbus-API - 在 c/Linux 中获取服务链接错误?

c - 使用逗号读取文本文件

c - 将数组地址作为函数参数传递

c++ - 位图算法

c - 为什么 Eclipse 生成的头文件以#ifndef 和#define 开头?

c - 用空格替换换行符并按特定行长度对单词进行排序

c - UDP 套接字编程——recvfrom() 一个端口和 sendto() 另一个端口