简体   繁体   中英

C program crashes just after giving last input

This program takes input from user product name, product class and product family and then stores it into a file. But after giving inputs and pressing enter program crashes saying product.exe has stopped working.

Here's the code-

#include <stdio.h>
#include <conio.h>

void add_new_product(void);
struct product
{
    char P_name;
    char P_class;
    char P_family;
}P[100];
FILE *fp;
void add_new_product()
{
    char ch;
    int i=0;
    fp=fopen("product.txt","w+");
       do
        {
            clrscr();
            printf("\t\t\t Add New Product");
            printf("\n User:");
            printf("\n\n\n \t\t\t 1.Product Name   :");
            printf("\n\n \t\t\t 2.Product Class  :");
            printf("\n\n \t\t\t 3.Product Family :");
            gotoxy(44,5);
            scanf("%s",&P[i].P_name);
            gotoxy(44,7);
            scanf("%s",&P[i].P_class);
            gotoxy(44,9);
            scanf("%s",&P[i].P_family);
            fprintf(fp,"%s %s %s %s %s %s",P[i].P_family,"|",P[i].P_class,"|",P [i].P_name,";");
        printf("\n \t\t Do you  want to add another product?(Y/N) :");
        scanf("%s",&ch);
        i++;
      }while((ch=='Y')||(ch=='y'));
        fclose(fp);
}

int main()
{
    add_new_product();
    getch();
    return 0;
}

}

as you are reading string from scanf you need to modify your structure as below:

#define MAX_LENGTH 100

struct product
{
    char P_name[MAX_LENGTH];
    char P_class[MAX_LENGTH];
    char P_family[MAX_LENGTH];
}P[100];

The correct code should be:

struct product
{
    char P_name[255];
    char P_class[255];
    char P_family[255];
}P[100];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM