I am new to C programming so bear with me here. I have been assigned a project where in which the user is prompted to enter a "part number, quantity, and price" when the user enters "0" the program ends, and the information is saved in a text file. A separate program gets compiled and then prints out what the user entered. Here is what the first program (save_inventory.c) prompts the user with.
This program stores a business inventory.
Please enter item data (part number, quantity, price): *3, 1, 2.4*
Please enter item data (part number, quantity, price): *1, 4, 3.0*
Please enter item data (part number, quantity, price): *0*
Thank you. Inventory stored in file inventory.txt.
And here is what the second program(display_inventory.c) is supposed to ouput:
Below are the items in your inventory:
Part# Quantity Item Price
3 1 $ 2.40
1 4 $ 3.00
2 4 $ 1.30
I have the code working so far, the only issue is that when I use my display_inventory.c program, the last line of the input is printed twice. So 2, 4, $ 1.30 appears again. Here is the code for both programs:
save_inventory.c:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int pn, q;
float p;
FILE *fp = fopen("inventory.txt", "wb");
printf("This program stores a business inventory.\n");
for(;;)
{
printf("Please enter item data (part number, quantity, price): ");
scanf("%d, ", &pn);
if(pn == 0){break ;}
scanf("%d, %f", &q, &p);
fwrite(&pn , sizeof(pn) ,1, fp);
fwrite(&q , sizeof(q),1 , fp);
fwrite(&p, sizeof(p) , 1,fp);
}
printf("Thank you. Inventory stored in file inventory.txt.\n");
fclose(fp);
return 0;
}
And here is display_inventory.c:
#include<stdio.h>
#include<stdlib.h>
int main()
{
int pn, q;
float p;
FILE *fp = fopen("inventory.txt", "rb");
printf("Part#\t Quantity\t Item Price");
for(;!feof(fp);)
{
fread(&pn , sizeof(pn) ,1, fp);
fread(&q , sizeof(q),1 , fp);
fread(&p, sizeof(p) , 1,fp);
printf("\n%5d\t %8d \t $%9.2f\n",pn,q,p);
}
fclose(fp);
return 0;
}
Since I have spent a bit of time trying to figure this one out, I figured I'd ask if anyone has any tips on how to not have the last entry printed out twice. Thank you!