C - 按零件编号升序显示零件

标签 c function sorting inventory

我是新来的,所以我不知道我是否正确发布了此信息。我做了老师告诉我们为这个项目要做的一切,但是最后一个让我难住了,因为我们从来没有在类里面谈论过排序。它说:“修改 print() 函数,使其显示按零件号升序排列的零件。”我试着翻阅书本和上网,但结果却让自己变得更加困惑。谁能帮我?这是我的代码:

#include <stdio.h>
#include <string.h>
#include <ctype.h>
#define NAME_LEN 25
#define MAX_PARTS 100

struct part {
int number;
char name[NAME_LEN + 1];
int on_hand;
float price;
};

int find_part(int number, const struct part inv[], int np);
void insert(struct part inv[], int *np);
void search(const struct part inv[], int np);
void update(struct part inv[], int np);
void print(const struct part inv[], int np);
int read_line(char [], int);

/**************************************************************
 * main:    Prompts the user to enter an operation code,      *
 *          then calls a function to perform the requested    *
 *          action. Repeats until the user enters the         *
 *          command 'q'. Prints an error message if the user  *
 *          enters an illegal code.                           *
 **************************************************************/
int main(void)
{   
char code;
struct part inventory[MAX_PARTS];
int num_parts = 0;

for (;;)
{
    printf("Enter operation code: ");
    scanf(" %c", &code);
    while (getchar() != '\n')    /* skips to end of line */
    {
        ;
    }

    switch (code)
    {
        case 'i':
            insert(inventory, &num_parts);
            break;

        case 's': 
            search(inventory, num_parts);
            break;

        case 'u':
            update(inventory, num_parts);
            break;

        case 'p': 
            print(inventory, num_parts);
            break;

        case 'q':
            return 0;

        default:
            printf("Illegal code\n");
            break;
    }

    printf("\n");
}
}

/************************************************************
 * find_part:   Looks up a part number in the inv array.    *
 *              Returns the array index if the part number  *
 *              is found; otherwise, returns -1.            *
 ************************************************************/
int find_part(int number, const struct part inv[], int np)
{
int i;

for (i = 0; i < np; i++)
{
    if (inv[i].number == number)
    {
        return i;
    }
}

return -1;
}

/****************************************************************
 * insert: Prompts the user for information about a new         *
 *               part and then inserts the part into the inv    *
 *               array. Prints an error message and returns     *
 *               prematurely if the part already exists or the  *
 *               array is full.                                 *
 ****************************************************************/
void insert(struct part inv[], int *np)
{
int part_number;

if (*np == MAX_PARTS)
{
    printf("Database is full; can't add more parts.\n");
    return;
}

printf("Enter part number: ");
scanf("%d", &part_number);

if (find_part(part_number, inv, *np) >= 0)
{
    printf("Part already exists.\n");
    return;
}

inv[*np].number = part_number;
printf("Enter part name: ");
read_line(inv[*np].name, NAME_LEN);
printf("Enter quantity on hand: ");
scanf("%d", &inv[*np].on_hand);
printf("Enter the price of the item: ");
scanf("%f", &inv[*np].price);
(*np)++;
}

/************************************************************
 * search:  Prompts the user to enter a part number, then   *
 *          looks up the part in the inv array. If the      *
 *          part exists, prints the name and quantity on    *
 *          hand; if not, prints an error message.          *
 ************************************************************/
void search(const struct part inv[], int np)
{
int i, number;


printf("Enter part number: ");
scanf("%d", &number);

i = find_part(number, inv, np);
if (i >= 0)
{
    printf("Part name: %s\n", inv[i].name);
    printf("Quantity on hand: %d\n", inv[i].on_hand);
    printf("Item Price: %.2f\n", inv[i].price);
}
else
{
    printf("Part not found.\n");
}
}

/*************************************************************
 * update:  Prompts the user to enter a part number.         *
 *          Prints an error message if the part can't be     *
 *          found in the inv array; otherwise, prompts the   *
 *          user to enter change in quantity on hand and     *
 *          updates the array.                               *
 *************************************************************/
void update(struct part inv[], int np)
{
int i, number, change, userChoice, changePartNum;
float changePrice;
char *changeName[] = {""};

printf("Enter part number: ");
scanf("%d", &number);

i = find_part(number, inv, np);
if (i >= 0)
{   
    printf("Enter your selection to edit this particular part:\n"
            "\t\t Type 1 to change the Part Number\n"
            "\t\t Type 2 to change the Part Name\n"
            "\t\t Type 3 to change the Price\n"
            "\t\t Type 4 to change the Quantity on Hand\n"
            "\t\t Type 5 to exit without making changes\n\n"
            "\t\t Enter your choice here: ");
    scanf("%d", &userChoice);
    switch ( userChoice )
        {
            //printf("Would you like to change the Part Number? \nType 1 for yes or 2 for no.");
            //scanf("%d", &userChoice);
            case 1:
                    printf("Enter new part number: ");
                    scanf("%d", &changePartNum);
                    inv[i].number = changePartNum;
                    printf("Change part num: %d\n", changePartNum);
                    printf("inv[i].number: %d\n", inv[i].number);
                    break;

            //printf("Would you like to change the Part Name? \nType 1 for yes or 2 for no.");
            //scanf("%d", &userChoice);
            case 2:
                    printf("Enter new name of part: ");
                    scanf("%s", changeName);
                    printf("Change part name: %s\n", changeName);
                    //strcpy (*changeName, inv[i].name[NAME_LEN + 1]);
                    //printf("&inv[i].name[NAME_LEN + 1]: %d\n", &inv[i].name[NAME_LEN + 1]);
                    break;


            //printf("Would you like to change the price? \nType 1 for yes or 2 for no.");
            //scanf("%d", &userChoice);
            case 3:
                    printf("Enter change in item price: ");
                    scanf("%f", &changePrice);
                    inv[i].price = changePrice;
                    break;

            //printf("Would you like to change the quantity on hand? \nType 1 for yes or 2 for no.");
            //scanf("%d", &userChoice);
            case 4:
                    printf("Enter change in quantity on hand: ");
                    scanf("%d", &change);
                    inv[i].on_hand = change;
                    break;
            case 5:
                printf("Exiting the editor.");
                break;
            default:
                printf("Your choice is not on the list.");
                break;
        }   
} 
else
{
    printf("Part not found.\n");
}
}

/************************************************************
 * print:   Prints a listing of all parts in the inv array, *
 *          showing the part number, part name, and         *
 *          quantity on hand. Parts are printed in the      *
 *          order in which they were entered into the       *
 *          array.                                          *                                                           *
 ************************************************************/
void print(const struct part inv[], int np)
{
int i;

printf("Part Number  Part Name       "
             "Quantity on Hand    "
             "  Price\n");
for (i = 0; i < np; i++)
{
    printf("%7d\t\t    %-5s%31d\t%.2f\n", inv[i].number,
                 inv[i].name, inv[i].on_hand, inv[i].price);
}
}

/*************************************************************
 * read_line:   Skips leading white-space characters, then   *
 *              reads the remainder of the input line and    *
 *              stores it in str.   Truncates the line if its *
 *              length exceeds n.   Returns the number of    *
 *              characters stored.                           *
 *************************************************************/
int read_line(char str[], int n)
{
int ch = 0;
int i = 0;

while (isspace (ch = getchar()))
{
    ;
}

while (ch != '\n' && ch != EOF)
{
    if (i < n)
    {
        str[i++] = ch;
    }

    ch = getchar();
}

str[i] = '\0';

return i;
}

最佳答案

如果您的教授允许您使用标准库中的函数,请查看 C library function to do sort ,它提供了一个答案,向您展示如何使用 qsort()。如果您使用的是 Linux,您还可以通过执行 man qsort 来获取有关该函数(以及其他标准库函数)的文档。 。如果您使用的不是 Linux,请查看各种在线手册页。

如果没有,您的教授可能希望您自己进行研究。通常,冒泡排序算法因其简单性而被教授给初学者。 rosettacode提供了冒泡排序的伪代码:

repeat
    hasChanged := false
    decrement itemCount
    repeat with index from 1 to itemCount
        if (item at index) > (item at (index + 1))
            swap (item at index) with (item at (index + 1))
            hasChanged := true
until hasChanged = false

请注意,在您的打印函数中,您已经拥有了所需的一切:数组及其长度。您通过循环遍历并打印出所有成员变量来演示了这一点。现在您只需要编写排序算法即可。该算法需要的一件事是比较器函数。您说您需要按零件号排序。这意味着您的比较器函数可能如下所示:

int compare(struct part a, struct part b)
{
    return (a.number < b.number);
}

对于qsort():

qsort(inv, np, sizeof(part), compare);

在您的排序算法中(您应该自己编写):

if (item.number at index) > (item.number at (index + 1))

关于C - 按零件编号升序显示零件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26027640/

相关文章:

c - 在 C 中打印 ASCII

javascript - 根据另一个引用 ID 数组按属性对对象数组进行排序

c++ - 字符串升序排列

c++ - 为什么 Clang 优化掉 x * 1.0 而不是 x + 0.0?

php - 如何处理 PHP 中已弃用的函数

php - 当我的页面加载时,它显示上一个 mysql 查询结果而不是当前的结果

javascript - 多个外部 javascript 文件 - 如何调用函数

mysql - 如何根据任意列条目列表返回 mysql 行?

java - 如何按字典顺序对 ArrayList 进行排序?

c - 函数参数中的数组名称的处理方式是否与本地声明的数组不同(自动)