我的代码不能把我输入的数据放在我的txt文件中,idk我做错了

时间:2013-12-12 15:08:25

标签: c file

      struct info
    {
    char code[4];
    char name[30];
    int quantity[3];
    float price[6];
    };
    void main()
    {
    FILE *f;
    int i,n,check;
    struct info ip;
    do
    {
    printf("How many products are about to input ?\n");
    fflush(stdin);
    check=scanf("%d",&n);
    if (check!=1) printf("Input again\n");
    }
    while (check!=1);
    f=fopen("products.txt","w");
    for (i=1;i<=n;i++)
    {
    printf("Input product code\n");
    gets(ip.code);
    fputs(ip.code,f);
    printf("Input product name\n");
    gets(ip.name);
    fputs(ip.name,f);
    printf("Input product quantity\n");
    scanf("%d",&ip.quantity);
    fprintf(f,"%d",&ip.quantity);
    printf("Input product price\n");
    scanf("%f",&ip.price);
    fprintf(f,"%f",ip.price);
    }
    }

我无法通过键盘输入用户输入并在我的txt文件中记下来,任何人都可以帮我解决我的错误,如果整件事情出错,请帮我一个样本。

1 个答案:

答案 0 :(得分:3)

哇!永远不要使用gets(),特别是永远不要使用四个字符这样的小缓冲区。

您的问题很可能是缓冲区溢出。

使用fgets()代替gets()来阅读字符串,它会更安全。更好的是fgets()进入一个“足够大”(比如128个字符)的临时行缓冲区,然后添加代码来检查并从中提取所需的值并将其存储在{{1}中}字段。这也使您有机会验证输入。