• Уважаемый Гость.
    - Прежде чем создать свою тему, пожалуйста, попробуй воспользоваться этим -> ПОИСКОМ !!!
    - После решения Вашего вопроса (проблемы) - нажмите "Лучший ответ", на сообщении, которое его решило. За игнорирование этого действия - Вы получите соответствующее предупреждение. Мы - стараемся Вам помочь. Уделите 10 секунд - чтобы нажать кнопку. (Если у Вас нет такой возможности - укажите в последнем своем сообщении какой ответ Вы считаете лучшим. Наши модераторы сделают это за Вас)
    ЗАПРЕЩЕНО:
    - Cоздавать темы с названиями "Помогите", "Плиз", "Ошибка", "Не могу найти", "Хелп" и тому подобное;
    - Cоздавать темы без детального описания того, что нужно исправить.
    - Cоздавать темы из одного скриншота.
    За игнор правил форума - Ваша тема будет удалена, а Вы получите системное предупреждение.

С++ / Создание функций и корректных вызовов

SporTsmaN

Изучающий
Пользователь
Регистрация
16 Апр 2013
Сообщения
744
Лучшие ответы
0
Репутация
218
всем здравствуйте. такое дело,нужно освободить по максимуму от кода main.cpp(то есть сделать case 1:вызов функции и так далее),все функции находятся в файле prog.cpp,соответственно,их объявление в header.h




header.h
Код:
    typedef struct Product
{
 char   name[100];
 char   country[100];
 char   manufacturer[100];
 int    article;
 int    price;
} Product ;

void        readArrayOfProduct(Product *S, int n);
void        sortProduct(Product *S, int n);
void        editProduct(Product *S, int k);
void        printArrayOfProduct(Product *S, int n);
int         findProduct(Product *S,int n,char* num);
int         save(Product *S, int n, char *fname);
int         load(Product *S, int n, char* fname);
Product*    addProduct(Product *S, int *pn,Product a);
Product*    deleteProduct(Product *S, int *pn,int k);
Product*    insertProduct(Product *S, int *pn,Product a,int k);
void        EnterKeyboard(Product * S, int n);
int         FreeAllocatedMem(Product * S, int n);
prog.cpp

Код:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include "header.h"
#include <conio.h>


void readArrayOfProduct(Product *S, int n)

{
    int i ;
    for( i = 0; i < n; i++ )
    {
        printf("product %d:\n ", i+1);
        printf("product name: ");
        
        fflush(stdin);
        fgets(S[i].name, sizeof(S[i].name), stdin);
        S[i].name[strcspn(S[i].name, "\n")] = 0;
        printf("product country: ");
        fflush(stdin);
        fgets(S[i].country, sizeof(S[i].country), stdin);
        S[i].country[strcspn(S[i].country, "\n")] = 0;
        printf("product manufacturer: ");
        fflush(stdin);
        fgets(S[i].manufacturer, sizeof(S[i].manufacturer), stdin);
        S[i].manufacturer[strcspn(S[i].manufacturer, "\n")] = 0;
        printf("product article: ");
        scanf("%d",&S[i].article);
        printf("product price: ");
        scanf("%d",&S[i].price);
    }
    return;
}

int findProduct(Product *S, int n, char* temp)
{
    int i;
    for( i = 0; i < n; i++ )
    {
        if( strcmp(S[i].name, temp) == 0)
        {
            return i;
        }
    }
    return -1;
}

void sortProduct(Product *S, int n)
{
    Product t;
    int i, k;
    for( i = 0; i < n; i++)
    {
        for( k = 0; k < n - 1 - i; k++)
        {
            //if( stricmp(S[k].name,S[k+1].name) >0 )
            if(S[k].price > S[k+1].price)         
            {
                t=S[k];
                S[k]=S[k+1];
                S[k+1]=t;
            }
        }
    }
    return;
}

void printArrayOfProduct(Product *S, int n)
{
    int i;
    for( i=0; i<n; i++)
    {
        printf("\n\n   Product: %d\n Name: %s\n Country: %s\n Manufacturer: %s\n Article: %d\n Price %d\n",i+1,
        S[i].name,S[i].country,S[i].manufacturer,S[i].article,S[i].price);
    }
    return;
}

void editProduct(Product *S, int k)
{
    int f;
    printf("To change product name? (1/0):  ");
    scanf("%d", &f);
    if( f != 0 )
    {
        printf("enter product name: ");
        fflush(stdin);
        fgets(S[k].name, sizeof(S[k].name), stdin);
    }
    
    printf("To change product country? (1/0):  ");
    scanf("%d", &f);
    if( f != 0)
    {
        printf("enter product country: ");
        fflush(stdin);
        fgets(S[k].country, sizeof(S[k].country), stdin);
    }
    
    printf("To change product manufacturer? (1/0):  ");
    scanf("%d", &f);
    if( f != 0 )
    {
        printf("enter product manufacturer:");
        fflush(stdin);
        fgets(S[k].manufacturer, sizeof(S[k].manufacturer), stdin);
    }
    
    printf("To change product article? (1/0):  ");
    scanf("%d", &f);
    if( f != 0 )
    {
        printf("enter product article: ");
        scanf("%d", &S[k].article);
    }
    printf("To change product price? (1/0):  ");
    scanf("%d", &f);
    if( f != 0 )
    {
        printf("enter product price: ");
        scanf("%d", &S[k].price);
    }
    return;
}




Product* addProduct(Product * S, int *pn, Product a)
{
    Product * B;
    B = (Product*)realloc(S,((*pn)+1)*sizeof(Product));
    if ( B == NULL )
    {
        return B;
    }
    B[*pn]= a;
    *pn=*pn+1;
    return B;
}

Product* deleteProduct(Product* S,int *pn, int k)
{
    Product *B;
   int i;
    for(  i=k; i<*pn-1; i++)
    {
        S[i]=S[i+1];
    }
    B=(Product*)realloc(S,((*pn)-1)*sizeof(Product));
    if(B==NULL)
    {
        return B;
    }
    *pn=*pn-1;
    return B;
}

Product* insertProduct(Product* S, int *pn,Product a,int k)
{
    Product * B;
    int i;
    B=(Product*)realloc(S,((*pn)+1)*sizeof(Product));
    if(B==NULL)
    {
        return B;
    }
    for( i=*pn-1; i>=k; i--)
    {
        B[i+1]=B[i];
    }
    B[k]=a;
    *pn=*pn+1;
    return B;
}

int save(Product* S, int n, char *fname)
{
    FILE *fp;
    int i;
    fp=fopen(fname,"w");
    if(fp==NULL)
    {
        return 0;
    }
    for(  i=0; i<n; i++)
    {
        fprintf(fp, "%s %s %s %d %d\n", S[i].name,S[i].country,S[i].manufacturer,S[i].article,S[i].price);
    }
    fclose(fp);
    return 1;

}

int load(Product * S, int n, char *fname)
{
    FILE *fp;
    int i;
    fp=fopen(fname,"r");
    if( fp == NULL )
    {
        return 0;
    }
    for(  i=0; i<n; i++)
    {
        fscanf(fp, "%s %s %s %d %d\n", S[i].name,S[i].country,S[i].manufacturer,S[i].article,S[i].price);
    }
    fclose(fp);
    return 1;

}

void EnterKeyboard(Product * S, int n)
{       
    if(!n)
    {
        puts("you need to allocate the memory in case 1 first!");
        getch();
    }
    else
    {
        puts("Enter the product details: ");
        readArrayOfProduct(S,n);
        puts("To continue Press the Enter key");
        getch();
    }
}

int FreeAllocatedMem(Product * S, int n)
{
    if(!n)
    {
        puts("error, you need to allocate the memory");
        puts("To continue Press the Enter key");
        getch();
        return 0;
    }
    else
    {
        free(S);
        S = NULL;
        puts("Memory release was successfully carried out");
        puts("To continue Press the Enter key");
        getch();
        n = 0;
        return 1;
    }
}
main.cpp

Код:
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<conio.h>
#include"prog.cpp"     



            
int main()
{
    Product *S, *B, a;
    char temp[50], fname[50];
    int n = 0,choise,f=0,k;
    
    while(1)
    {
        system("cls");
        puts("\t MENU:");
        puts("1. Dynamic memory allocation for structures ");
        puts("2. Entering the panel elements from the keyboard ");
        puts("3. Search for the array element ");
        puts("4. Sorting array elements ");
        puts("5. Editing the element of the table ");
        puts("6. Adding a new item at the end ");
        puts("7. Removing the indicated item from the table ");
        puts("8. Inserting a new item ");
        puts("9. Saving array elements to file ");
        puts("10. Reading array elements from the file ");
        puts("11. Print array of Product ");
        puts("12. Free the memory allocated for the array ");
        puts("0.  Exiting the program ");

        printf("\nChoose the option from the menu: ");
        scanf("%d", &choise);

        switch(choise)
        {
        case 1:
                
      
            printf("Enter the number of products: ");
            scanf("%d", &n);

            S= (Product*)malloc(n*sizeof(Product));
            if( S == NULL )
            {
                puts("No memory was allocated");
                exit (1);
            }
            puts("Memory was successfully allocated");
            puts("To continue Press the Enter key");
            getch();
            f = 1;
            break;
        case 2:
            
            
            EnterKeyboard(S, n);
            break;
        case 3:
            puts("Enter the product name to search for: ");
            fflush(stdin);
            gets(temp);
            k = findProduct(S,n,temp);
            if( k < 0 )
            {
                puts("The search failed. The product was not found in the database");
            }
            else
            {
                puts("Product Information: ");
                printf(" Name: %s\n Country: %s\n Manufacturer: %s\n Article: %d\n Price: %d\n",
                S[k].name,S[k].country,S[k].manufacturer,S[k].article,S[k].price);
            }

            puts("To continue Press the Enter key");
            getch();
            break;
        case 4:
            sortProduct(S, n);
            puts("Sorting completed successfully");
            puts("To continue Press the Enter key");
            getch();
            break;
        case 5:
            puts("Enter the product name to modify:");
            fflush(stdin);
            gets(temp);
            k = findProduct(S,n,temp);
            if( k < 0 )
            {
                puts("The search failed. The product was not found in the database");
            }
            else
            {
                puts("Product Information: ");
                printf(" Name: %s\n Country: %s\n Manufacturer: %s\n Article: %d\n Price: %d\n",
                S[k].name,S[k].country,S[k].manufacturer,S[k].article,S[k].price);
                editProduct(S,k);
            }

            puts("To continue Press the Enter key");
            getch();
            break;
        case 6:
            if(!n)
            {
                puts("you need to allocate the memory in case 1 first!");
                getch();
            }
            else
            {
                puts("Enter the product information to add: ");
                printf("Enter the product name: ");
                fflush(stdin);
                fgets(a.name, sizeof(a.name), stdin);
                a.name[strcspn(a.name, "\n")] = 0;
                printf("Enter the product country: ");
                fflush(stdin);
                fgets(a.country, sizeof(a.country), stdin);
                a.country[strcspn(a.country, "\n")] = 0;
                printf("Enter the product manufacturer: ");
                fflush(stdin);
                fgets(a.manufacturer, sizeof(a.manufacturer), stdin);
                a.manufacturer[strcspn(a.manufacturer, "\n")] = 0;
                printf("Enter the product article: ");
                scanf("%d",&a.article);
                printf("Enter the product price: ");
                scanf("%d",&a.price);
                B=addProduct(S, &n, a);
                if ( B == NULL )
                {
                    puts("Adding the item at the end did not occur");
                }
                else
                {
                    puts("Adding the item at the end was successful");
                    S=B;
                }
    
                puts("To continue Press the Enter key");
                getch();
            }
            
            
            break;
        case 7:
            puts("Enter the product name to delete: ");
            fflush(stdin);
            gets(temp);
            k=findProduct(S,n,temp);
            if(k<0)
            {
                puts("The search failed. The product was not found in the database");
            }
            else
            {
                puts("Product Information: ");
                printf(" Name: %s\n Country: %s\n Manufacturer: %s\n Article: %d\n Price: %d\n",
                S[k].name,S[k].country,S[k].manufacturer,S[k].article,S[k].price);
                B=deleteProduct(S, &n, k);
                if( B == NULL )
                {
                    puts("Item deletion did not occur");
                }
                else
                {
                    puts("Item deletion was successful");
                    S = B;
                }
            }
            puts("To continue Press the Enter key");
            getch();
            break;

        case 8:
            
            if(!n)
            {
                puts("error, you need to allocate the memory");
                puts("To continue Press the Enter key");
                getch();
            }
            else
            {
                puts("Enter the product information to insert: ");
                printf("Enter the product name: ");
                fflush(stdin);
                fgets(a.name, sizeof(a.name), stdin);
                a.name[strcspn(a.name, "\n")] = 0;
                printf("Enter the product country: ");
                fflush(stdin);
                fgets(a.country, sizeof(a.country), stdin);
                a.country[strcspn(a.country, "\n")] = 0;
                printf("Enter the product manufacturer: ");
                fflush(stdin);
                fgets(a.manufacturer, sizeof(a.manufacturer), stdin);
                a.manufacturer[strcspn(a.manufacturer, "\n")] = 0;
                printf("Enter the product article: ");
                scanf("%d",&a.article);
                printf("Enter the product price: ");
                scanf("%d",&a.price);
                printf("Enter the insertion position: ");
                scanf("%d", &k);
                B = insertProduct(S, &n, a,k-1);
                
                if( B == NULL )
                {
                    puts("The insertion of the element did not occur");
                }
                else
                {
                    puts("The insertion of the element was successful");
                    S = B;
                }
    
                puts("To continue Press the Enter key");
                getch();
            }
            break;
        case 9:
        
            
            puts("Enter the file name when you want to stdin:");
            fflush(stdin);
            gets(fname); 
        
            f = save(S,n,fname); 
            if( f == 1 )
            {
                puts("saving in the file was successful"); 
            }
            else
            {
                puts("The file to read product information has not been opened");
            }
            puts("To continue Press the Enter key");
            getch();
            break;
        case 10:
            puts("Enter the file name when you want to stdout:");
            fflush(stdin);
            gets(fname);
            f = load(S,n,fname);
            if( f == 1 )
            {
                puts("Reading from the file was successful");
            }
            else
            {
                puts("The file to read product information has not been opened");
            }
            puts("To continue Press the Enter key");
            getch();
            break;
        case 11:
            puts("Product Information: ");
            printArrayOfProduct(S, n);
            puts("To continue Press the Enter key");
            getch();
            break;
        case 12:
            
            
            if(FreeAllocatedMem(S, n)) n = 0;
            break;
        case 0:
            printf("Do you want to leave the program? (1/0): ");
            scanf("%d", &f);
            if( f == 1)
            {
                return 0;
            }
            puts("To continue Press the Enter key");
            getch();
            break;
        default:
            puts("This command does not exist.\nChoose the correct option from the menu! ");
            puts("To continue Press the Enter key");
            getch();
        }

    }
}
 
Сверху Снизу