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 回答
首先,您需要声明一个有意义的结构 . 该结构包含每个项目的相关信息 . 例:
接下来,您需要一个这种结构的数组 . 使用
malloc
为total
项目分配足够的内存 . 例:现在你有
beers[0], beers[1], beers[2]...
,读取文件中的每个项目并将其放入结构中 .要读取文件,可以使用
fscanf
或fgets
.您文件中的第一行是
您可以使用
fscanf
读取数字7
:这应该可以正常工作,但是有一些你不感兴趣的字符 . 使用
fgets
读取到行尾并丢弃这些字符 .开始循环并读取每一行,添加到结构中 .
使用此方法,如果要添加新项,则必须增加内存大小 . 见
add_item
,它使用realloc
. 这可能太先进了 . 或者,您可以将新项目保存到文件中,调用free(beers)
,然后再次读取该文件 .