I try to do a simple database with records from input and write them into a file. But when I run the program ,it only work for first record. I need to say that the file has been created and the first record was written.
#include <stdio.h>
struct produs {
char nume[20];
float cantitate,pret_tot,pret_unit;
};
void main(void) {
struct produs prod;
int i;
char n;
FILE *fisier;
fisier = fopen("C:\\Users\\amzar\\Desktop\\Programe PC\\Tema suplimentara\\C_3\\tema_c_3\\fisier.txt","w");
printf("\nApasati tasta [d/n] pentru a continua sau nu interogarile!\n");
do {
printf("\nIntroduceti numele produsului: ");
fgets(prod.nume,sizeof(prod.nume),stdin);
scanf("%f\n%f\n%f",&prod.pret_unit,&prod.cantitate,&prod.pret_tot);
fprintf(fisier,"Numele produsului: %s \nPret unitar: %.2f \nCantitate: %.2f kg \nPret total: %.2f",prod.nume,prod.pret_unit,prod.cantitate,prod.pret_tot);
} while((n = getche()) != 'n');
fclose(fisier);
}
Your problem happens when you use
getche()
and you don't discard the\n
that it leaves on the buffer.Also note that I didn't use
fgets
to not include\n
inprod.nume
.Correct code: