首页 文章

如何利用struct数组根据用户输入输出给定的结构

提问于
浏览
2

ISSUE: 我正在尝试用 beer.dat 中的数据填充我的 beerData struct ,除了我不明白结构如何工作得很好而不会崩溃我的代码 . 我相信我需要一系列结构 .

The beer.dat file contents:

7 // total number of beers 
Coors //beer name
1234567 // beer id
72 // beer quantity
7.40 //beer price 
Miller
7777777
44
9.70
Bud
7654321
345
9.90
Wachusett
7799435
4
14.70
Corona
9999999
112
9.99
Zima
0000000
1
0.01
Mikes
0890398
12
10.99

CODE:

/*
    User interface, alloc, malloc 13 points
    Correct structure and array built 7 points
    Recursive sort
 */

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

struct beerData {
    char *beer[7]; // number of brands

    char *beer_name; //names
    int beer_id[7]; //ID number given to beer
    int beer_quantity; //stock
    float beer_price; // pricing
} beer_data;


void printStr(char *line) {

    char *look = "";
    printf("What would you like to search for? \n");
    scanf("%s", look);

    //printf("Line: %s\n", line);


    exit(0);
}

void search() {
    //look through beer.dat for a specific beer by ID number.
    char str[32];

    FILE *fp = fopen("beer.dat", "r");

    if (fp == NULL) {
        printf("Error: can't open file to read\n");
    } else {
        while (!feof(fp)) {
            fscanf(fp, "%s ", str);
            //printf("%s\n",str);
            printStr(str);
        }

    }

    fclose(fp);
}


int main() {

    int user_choice;
    printf("Enter 1 to search for a beer, 2 to view the entire catalogue,"
           " and 3 to place an order, press 4 to exit.\n");


    while (user_choice != 4) {
        scanf("%d", &user_choice);
        switch (user_choice) {

            case 1:
                printf("Searching for a beer\n");
                user_choice = 0;
                search();
                break;
            case 2:
                printf("Viewing Inventory\n");
                //viewInv();
                break;
            case 3:

                printf("Placing an order...\n");
                //placeOrder();
                break;
            case 4:
                printf("Goodbye!\n");
                exit(0);
            default:
                printf("Incorrect entry, try again.\n");
                continue;
        }
    }


}

我正在尝试创建一个搜索文件的函数,并根据给定的ID查找特定的啤酒,该ID位于应该是其结构的集合内...所以一旦输入了ID,程序就会搜索啤酒,并打印出名称,ID,数量和价格 .

为了完全清楚,我会发布作业问题,以防我没有正确地传达我的需求 . 任务是:

  • 搜索啤酒应提示用户输入身份证号码,结果应显示其数量和价格(如果在您的库存中) .

  • 整个库存的视图将按价格按升序显示所有啤酒的ID号,价格和数量 . 这种排序应该使用Recursive Bubble或Recursive Selection排序 .

  • 下订单时,应在屏幕上打印订单发票 .

1 回答

  • 1

    首先,您需要声明一个有意义的结构 . 该结构包含每个项目的相关信息 . 例:

    typedef struct beer_data 
    {
        char name[20]; //names
        int id; //ID number given to beer
        int quantity; //stock
        float price; // pricing
    } beer_data;
    

    接下来,您需要一个这种结构的数组 . 使用 malloctotal 项目分配足够的内存 . 例:

    beer_data *beers = malloc(total * sizeof(beer_data));
    

    现在你有 beers[0], beers[1], beers[2]... ,读取文件中的每个项目并将其放入结构中 .

    要读取文件,可以使用 fscanffgets .

    您文件中的第一行是

    7 // total number of beers
    

    您可以使用 fscanf 读取数字 7

    int maximum = 0;
    fscanf(fp, "%d", &maximum);
    

    这应该可以正常工作,但是有一些你不感兴趣的字符 . 使用 fgets 读取到行尾并丢弃这些字符 .

    开始循环并读取每一行,添加到结构中 .

    使用此方法,如果要添加新项,则必须增加内存大小 . 见 add_item ,它使用 realloc . 这可能太先进了 . 或者,您可以将新项目保存到文件中,调用 free(beers) ,然后再次读取该文件 .

    typedef struct beer_data 
    {
        char name[20]; //names
        int id; //ID number given to beer
        int quantity; //stock
        float price; // pricing
    } beer_data;
    
    void search_by_name(beer_data *beers, int total)
    {
        char buf[20];
        printf("Enter name to search: ");
        scanf("%19s", buf);
        //note, we put %19s because beers[count].name is only 20 bytes long
    
        for(int i = 0; i < total; i++)
        {
            if(strcmp(beers[i].name, buf) == 0)
            {
                printf("Found: %s, %d, %d, %.2f\n",
                    beers[i].name, beers[i].id, beers[i].quantity, beers[i].price);
                return;
            }
        }
        printf("%s not found\n", buf);
    }
    
    void print_list(beer_data *beers, int total)
    {
        for(int i = 0; i < total; i++)
        {
            printf("%s %d %d %.2f\n",
                beers[i].name, beers[i].id, beers[i].quantity, beers[i].price);
        }
    }
    
    void add_item(beer_data *beers, int *total)
    {
        //note, total has to be passed as pointer 
        //because we are changing it
    
        //allocate more memory:
        beers = realloc(beers, sizeof(beer_data) * (*total + 1));
    
        printf("enter name: "); 
        scanf("%19s", beers[*total].name);
    
        printf("enter id:");
        scanf("%d", &beers[*total].id);
    
        printf("enter quantity:");
        scanf("%d", &beers[*total].quantity);
    
        printf("enter price:");
        scanf("%f", &beers[*total].price);
    
        //increase the total
        *total += 1;
    }
    
    int main() 
    {
        FILE *fp = fopen("beer.dat", "r");
        if(!fp)
        {
            printf("Error: can't open file to read\n");
            return 0;
        }
    
        char buf[500];
    
        int maximum = 0;
        fscanf(fp, "%d", &maximum);
    
        //read the rest of the line and discard it 
        fgets(buf, sizeof(buf), fp);
    
        //allocate memory
        beer_data *beers = malloc(maximum * sizeof(beer_data));
    
        int total = 0;
        while(1)
        {
            fgets(buf, sizeof(buf), fp);
            sscanf(buf, "%19s", beers[total].name);
    
            if(fscanf(fp, "%d", &beers[total].id) != 1) break;
            fgets(buf, sizeof(buf), fp);
    
            if(fscanf(fp, "%d", &beers[total].quantity) != 1) break;
            fgets(buf, sizeof(buf), fp);
    
            if(fscanf(fp, "%f", &beers[total].price) != 1) break;
            fgets(buf, sizeof(buf), fp);
    
            total++;
            if(total == maximum)
                break;
        }
    
        fclose(fp);
    
        int stop = 0;
        while (!stop)
        {
            printf("\
        Enter 0 to exit\n\
        Enter 1 print list\n\
        Enter 2 for search\n\
        Enter 3 add new item\n");
    
            int choice;
            scanf("%d", &choice);
            switch(choice)
            {
            case 0: 
                stop = 1;
                break;
    
            case 1:
                print_list(beers, total);
                break;
    
            case 2:
                search_by_name(beers, total);
                break;
    
            case 3:
                add_item(beers, &total);
                break;
            }
            printf("\n");
        }
    
        //cleanup:
        free(beers);
    
        return 0;
    }
    

相关问题