所以我一直试图理解定期定义的结构之间的区别,而不使用确实使用malloc的malloc链表。
我现在遇到的问题是尝试搜索结构(pi)以查找成本高于搜索输入成本的每个部件号。到目前为止,这是我的整个计划。我为每个部分添加了评论。
我只是不确定我是如何搜索每个结构以将其价格与搜索价格进行比较的。
#include <stdio.h>
#include <stdlib.h>
struct Item {
int quantity;
float cost;
char partNum[10];
struct Item *next;
};
void printItem(struct Item* pi);
void enterItem(struct Item* pi);
char search [100];
void main(int argc, char* argv[])
{
struct Item *pi;
struct Item *head;
int done = 0;
int i,j;
char choice;
// ENTERING ITEM INTO THE STRUCTURE
head = NULL;
while (!done) {
printf("Enter another item? (y/n)");
choice = getchar();
if (choice == 'y' || choice == 'Y') {
pi = (struct Item *)malloc(sizeof(struct Item));
enterItem(pi);
pi->next = head;
head = pi;
} else {
done = 1;
}
}
// SEARCHING FOR ITEM BY PRICE
printf("Enter a price to find all items more expensive, or type 'exit':");
while (strcmp(search, "exit") !=0) {
gets(search);
for (j = 0; j<i ; i++) {
if (strcmp(pi[j].cost, search) ==0) {
printItem(pi);
pi = pi->next;
}
}
}
}
getchar();
getchar();
}
// FUNCTION FOR PRINTING STRUCTURE ITEM
void printItem(struct Item* pi) {
printf("Quantity: %d\n", pi->quantity);
printf("Cost: $%.2f\n", pi->cost);
printf("Part # %s\n", pi->partNum);
printf("\n\n");
}
// FUNCITON FOR ENTERING IN NEW ITEM
void enterItem(struct Item* pi) {
printf("Quantity? ");
scanf("%d", &pi->quantity);
printf("Cost? ");
scanf("%f", &pi->cost);
getchar(); //need to clear out the carriage return from typeing in the cost
printf("Part Number? ");
gets(pi->partNum);
}
答案 0 :(得分:0)
你做错了是使用search
将字符串(cost
变量)与float(strcmp
变量)进行比较。这不会给你想要的输出。
相反,让我们使用-1
来表示exit
,因为解析字符串并将其转换为float是非主题的。开始从head
迭代到查找NULL
,并比较每个项目的价格。
float price;
struct Item *it = head;
printf("Enter a price to find all items more expensive, or type '-1' to exit:");
scanf("%f", price);
// check price for the 'exit' -- compare with -1
while (it != NULL) {
if (it->cost > price)
printItem(pi);
it = it->next;
}