在给出最后一个输入后C程序崩溃

时间:2015-06-09 17:23:01

标签: c

此程序从用户产品名称,产品类别和产品系列中获取输入,然后将其存储到文件中。但在输入并按下输入程序崩溃后,说product.exe已停止工作。

这是代码 -

#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;
}

}

2 个答案:

答案 0 :(得分:1)

当您从scanf阅读字符串时,您需要修改structure,如下所示:

#define MAX_LENGTH 100

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

答案 1 :(得分:1)

正确的代码应该是:

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