我尝试使用输入中的记录创建一个简单的数据库,并将它们写入文件。但是当我运行程序时,它只适用于第一个记录。我需要说文件已经创建并且写了第一条记录。
#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);
}
答案 0 :(得分:0)
当您使用getche()
时,您的问题就会发生,并且您不会丢弃它在缓冲区上留下的\n
。
另请注意,我没有使用fgets
在\n
中不包含prod.nume
。
正确的代码:
#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");
char buffer;
do {
printf("\nIntroduceti numele produsului: ");
/*
fgets includes the newline character in the string.
this instruction, instead, exlcudes it (%[^\n]) and discard it (%*c)
*/
scanf("%[^\n]%*c", prod.nume);
scanf("%f\n%f\n%f",&prod.pret_unit,&prod.cantitate,&prod.pret_tot);
//added '\n' at the end of each struct data
fprintf(fisier,"Numele produsului: %s \nPret unitar: %.2f \nCantitate: %.2f kg \nPret total: %.2f\n",prod.nume,prod.pret_unit,prod.cantitate,prod.pret_tot);
//input validation for inattentive users
do{
//this printf should be before reading the user choice (d/n)
printf("\nApasati tasta [d/n] pentru a continua sau nu interogarile!\n");
//here is your error: getche reads the character, but leaves the \n in the buffer...
}while((n = getche()) != 'n' && n != 'd');
//...so we have to clean the buffer to not skip next inputs
scanf("%c", &buffer);
}while(n == 'd');
fclose(fisier);
}