用于打印未排序数组的唯一元素的 C 程序

标签 c

基本上,我试图获得 5 个独特的草药列表(在本例中),包括库存编号、价格等。

在为我的数组获得 1 个列表后,我想使用一个函数来显示库存少于 5 的列表及其唯一代码(1,2,3..)如果没有打印“not run low on任何草药”并将它们存储在文本文件中。

我的问题是如何执行我在第 2 段中描述的操作。在案例 2 中调用一个函数,该函数将显示库存少于 5 种的所有草药并将它们保存在文本文件中。

非常感谢任何帮助!

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

#define user "kaiti"
#define pass "123pass!"
#define herbs 5

**void stock(int i, int code[herbs], int quantity[herbs])
{   
    for (i=0;i<herbs;i++){
    if(quantity[i]<5)
        printf("%d \t %d",code[i], quantity[i]);        
}
}**


int main()
{
    float price[herbs];
    char username[20], password[20];
    int option, i, code[herbs], quantity[herbs], consumption[herbs], choice;
//-----LOGIN PHASE-----
printf("Please Enter username:");
scanf("%s",username);

printf("\nPlease enter password:");
scanf("%s",password);

while(strcmp(username, user) != 0  || strcmp(password, pass) != 0)
 {
printf("Wrong username or password try again!\n"); 
printf("\nPlease Enter username:");
scanf("%s",&username);

printf("\nPlease enter password:");
scanf("%s",&password);
}

    printf("\nCorrect username and password.\n\nWelcome Mrs.Kaiti!\n\nWhat would you like to do?");
//-----END OF LOGIN PHASE-----

printf("\n(1)Register Herbs.\n**(2)Display herbs with stock less than 5 and store them in a text file.**\n(3)See the recomended daily dosage of a herb.\n(4)Add or deduct quantity of a herb.\n(5)Sell a herb.\nChoice: ");
scanf("%d",&option);

switch( option )
{
    case 1:

        for(i=0;i<herbs;i++){

        printf("Enter herb code: ");
        scanf("%d",&code[i]);
        printf("Enter herb quantity: ");
        scanf("%d",&quantity[i]);
        printf("Enter recomended daily consumption: ");
        scanf("%d",&consumption[i]);
        printf("Enter price: ");
        scanf("%f",&price[i]);
        printf("Add another herb?\n(1)Yes.\n(2)Back to login screen.\n");
        scanf("%d",&choice);
        if (choice == 2)
            return main()   ;
        }

    **case 2:

        printf("The Following herbs have a quantity less than 5: \n Code\t quantity \n");
        stock(i, code, quantity);**

最佳答案

您需要做的就是将 printf 替换为 fprintf,如下所示:

void stock(int code[herbs], int quantity[herbs])
{   
    int i;
    FILE *f = fopen("herbs_file_name", "w");

    for (i = 0 ; i < herbs ; i++)
    {
        if(quantity[i] < 5)
        {
            fprintf(f, "%d \t %d\n", code[i], quantity[i]);
        }
    }
    fclose(f);
}

请注意,您不需要传递 i - 只需在本地声明即可。

关于用于打印未排序数组的唯一元素的 C 程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42913521/

相关文章:

c++ - MinGW 不喜欢评论

c++ - 将 C 数组分配给 C+ +'s std::array? (std::array<T,U> = T[U]) - no suitable constructor exists from "T [U ]"to "std::array<T,U>"

c++ - 如何在 C/C++ 中将字符串从 UTF8 转换为 Latin1?

c - GTK+2 与 GTK+3 信号 "expose/draw/render"事件

c - 这段代码有什么问题?

C++ 二维数组函数 - 为什么第二个索引不能可变

c - 二维数组混淆(C程序)

c - 测试关闭的套接字

c - POSIX 信号量 : Why come the parent process acquire semaphore before child releases it?

c - 当输入是 int 和 string 的混合时,scanf 读取两次