Alif Khair
Alif Khair

Reputation: 89

C programming FILE output of struct array

After running the code with the following inputs, a runtime error occurs:

id : 123
name : stackoverflow
quantity : 123
price : 123

I need help to solve this.

Previously, I put the ampersand/& at:

fprintf(fp, "%d %s %d %d\n\n", a.id, a.name, a.quantity, a.price);

And a funny number came out:

2686724 stackoverflow 2686688 2686720

Code:

#include <stdio.h>
#include <stdlib.h>
#include <windows.h>
#include <ctype.h>
#include <conio.h>

struct product
{
    int quantity, reorder, i;
    char name[20];
    float price, id;
};


int main()
{

    FILE * fp;  

    int i=0;
    struct product a;
    system("cls");

    char checker;

    int counter;
    do
    {
        fp = fopen("addproduct.txt","a+t");
        system("cls");

        printf("Enter product ID : ");
        scanf(" %d", &a.id);

        printf("Enter product name : ");
        scanf(" %s", a.name);

        printf("Enter product quantity : ");
        scanf(" %d", &a.quantity);

        printf("Enter product price : ");
        scanf(" %d", &a.price);

        fprintf(fp, "%d %s %d %d\n\n", a.id, a.name, a.quantity, a.price);

        printf("Record saved!\n\n");

        fclose(fp);

        printf("Do you want to enter new product? Y / N : ");

        scanf(" %c", &checker);
        checker = toupper(checker);
        i++;
        system("cls");
    }
    while(checker=='Y');

    return(0);
}

Upvotes: 0

Views: 57

Answers (3)

Tonmoay Deb
Tonmoay Deb

Reputation: 1

There is a simple mistake. Here, the main issue is a collision between integer and float. You can change the 'id' & 'price' to 'int' from 'float' and it will solve the issue! Also, you can modify %d with %f when you are taking float input and output for price and id. I don't know why you declared 'id' as 'float' :|

Upvotes: 0

A.Varma
A.Varma

Reputation: 10

you have declared id,price as float data type . use %f instead of %d in the scanf statement.

Upvotes: 0

v.coder
v.coder

Reputation: 1932

It is because & points to the reference of the variable. Instead please try printing a.id.

fprintf (fp, "%d%s %d %d\n\n", a.id, a.name, a.quantity, a.price)

Upvotes: 1

Related Questions