【发布时间】:2019-05-01 16:25:52
【问题描述】:
我创建文件,我想从用户那里获取信息并写入文件或从数据中读取信息?我想在 Switch 中使用
我用来将数据写入文件的代码:fwrite(&x, sizeof(struct userRec), 1, fout);
fclose(fout);
我用来将数据写入文件的代码:fread(&x, sizeof(struct userRec), 1, fin);
当我尝试在文件中写入一些信息并使用记事本打开时,我只看到一些 NULL 字符。
struct userRec{
char firstName[25];
char lastName[25];
int UserID;
int day;
int month;
int year;
char adress[200];
float money;
};
int main(){
struct userRec user;
struct userRec x;
int menu1, answer;
char login[10];
char answer2;
char file_name[100];
float deposit, withdraw;
printf("Welcome to the IAU BANK !\n");
printf("Please enter any character to sign in : ");
scanf("%c",&login);
printf("\n\n\tMENU\n1.Create User Registration\n2.Login to Account\n");
scanf("%d",&menu1);
switch (menu1){
case 1:
printf("Please write your ID Number : ");
scanf("%s",&file_name);
FILE *fout;
fout = fopen(file_name , "wb");
printf("Please Enter Your First Name : ");
scanf("%s",&x.firstName);
printf("Please Enter Your Last Name : ");
scanf("%s",&x.lastName);
printf("Please Enter Your Identification Number Again : ");
scanf("%d",&x.UserID);
printf("Please Enter Your Birthday Date (dd/mm/yyyy) Format : ");
scanf("%d / %d / %d",&x.day,&x.month,&x.year);
printf("Please Enter Your Adress : ");
scanf("%s",&x.adress);
printf("\n\n\tYour Information is :\nFirst Name : %s\nLast Name : %s \nIdentification Number : %d \nBirthday Date : %d/%d/%d\nAdress : %s",x.firstName,x.lastName,x.UserID,x.day,x.month,x.year,x.adress);
printf("\n\n\tDo You Approve Your Information ? Yes:5 No:6 Enter 5 or 6\n");
scanf("%d",&answer);
case 5:
printf("Your information has been saved!\n");
fwrite(&user, sizeof(struct userRec), 1, fout);
fclose(fout);
printf("\nPress the 2 button to log in to your account : ");
scanf("%d",&answer);
case 2:
printf("Please write your ID Number : ");
scanf("%s",&file_name);
FILE *fin;
fin = fopen(file_name , "r");
fread(&x, sizeof(struct userRec), 1, fin);
printf("Welcome %s %s your ID : %d Your Date : %d / %d / %d Your Address : %s", x.firstName,x.lastName,x.UserID,x.day,x.month,x.year,x.adress);
printf("\nThe amount of money in your account : %.2f",x.money);
printf("\n\n\tMENU\n3.Deposit Money\n4.Withdraw Money\n");
scanf("%d",&menu1);
break;
case 3:
printf("Please enter the amount of money you want to deposit : ");
scanf("%f",&deposit);
printf("\nThe amount of money you deposit : %.2f\n", deposit);
x.money = deposit + x.money;
fwrite(&x, sizeof(struct userRec), 1, fout);
fclose(fout);
printf("\nThe total amount of money you deposit : %.2f\n",x.money);
break;
case 4:
printf("Please enter the amount of money you want to withdraw : ");
scanf("%f",&withdraw);
}
}
【问题讨论】:
-
你的流程一团糟。您在几个
case中打开一个文件但不关闭它,然后在另一个case中关闭它。您如何跟踪应该打开和关闭哪个?你有两个不同的userRec结构,x和user,哪一个在哪个时间点有效?如果你填写user然后保存x呢?或者读入user并显示x?switch中也有很多失败点,因此也很难跟进。 -
不要将
case 5:放在case 1:和case 2:之间。不要忘记在每个case块的末尾包含break;。使用函数。 -
@Someprogrammerdude — 因为变量声明不是紧跟在 case 标签之后,所以允许它们不加注释。变量的范围很奇怪,但代码实际上并没有编译器可报告的问题。