【发布时间】:2021-07-12 09:52:59
【问题描述】:
我正在尝试创建一个程序,在 switch case 4 中将记录添加到文件中,但它不断地循环。有人可以在这里帮忙吗?我希望它添加一个学生的记录,然后跳出那个案例并进入主菜单。
我是 C 编程新手,不熟悉 switch case。请看一下,让我知道我需要更改什么。
我认为问题出在开关盒期间,而不是实际代码,因为我确实创建了任何循环,所以我试图了解开关盒的哪一部分需要更改,或者是否有更好的方法来做到这一点。
int createFile();
char writeFile();
void mainMenu();
struct Update
{
char studentName[50];
int studentID;
char emailID[100];
char courseID[5];
int grade;
} update2;
int main ()
{
int num;
do
{
printf(" M A I N M E N U \n");
printf("1. Create the Binary File\n");
printf("2. Display Contents of the file\n");
printf("3. Seek a specific record\n");
printf("4. Update the contents of a record\n");
printf("5. Delete a record for the specific name\n");
printf("6. Exit\n");
switch(num)
{
case 1:
createFile();
break;
case 4:
writeFile();
mainMenu();
break;
case 6:
break;
}
scanf("%d", &num);
} while (num != 6);
return 0;
}
int createFile() {
FILE *fp;
fp = fopen ("BINARY_FILE.txt", "w");
printf("created file called BINARY_FILE.txt\n");
return 0;
}
char writeFile() {
FILE *fp;
fp = fopen ("BINARY_FILE.txt", "w");
int j;
int i =0;
printf("Enter the studentID\n");
scanf("%d", &update2.studentID);
fprintf(fp, "the studentID:%d\n",update2.studentID);
printf("Enter the student name\n");
scanf("%s", update2.studentName);
fprintf(fp, "the student name:%s\n",update2.studentName);
printf("Enter the emailID\n");
scanf("%s", update2.emailID);
fprintf(fp, "the emailID:%s\n",update2.emailID);
printf("Enter the courseID\n");
scanf("%s", update2.courseID);
fprintf(fp, "the courseID:%s\n", update2.courseID);
printf("Enter the grade\n");
scanf("%d", &update2.grade);
fprintf(fp, "the grade:%d\n", update2.grade);
fclose(fp);
return 0;
}
void mainMenu()
{
printf(" M A I N M E N U \n");
printf("1. Create the Binary File\n");
printf("2. Display Contents of the file\n");
printf("3. Seek a specific record\n");
printf("4. Update the contents of a record\n");
printf("5. Delete a record for the specific name\n");
printf("6. Exit\n");
}
【问题讨论】:
-
num未初始化?还是在某处缺少scanf()? -
你应该把 scanf 放到外面和里面,或者重新排序你的代码
-
您正在开启
num在读取任何值之前。 -
旁注:
mashed_potaotes->mashed_potatoes??? -
已更新我的答案。看看最后的建议是否有帮助?
标签: c