这里是我的代码,我的陈述是,while循环开始运行show选项并在第一次迭代时扫描选择,但在第二次迭代中,不会再次指定选择,并且会记住先前的选择。问题是什么 ? (我正在使用VS2012)C项目scanf()
while (!done){
int choice;
printf("\n------- STUDENT INFORMATION SYSTEM MAIN MENU --------\n");
printf("1-Load students from the database\n");
printf("2-Print existing students on the screen\n");
printf("3-Add a new student\n");
printf("4-Delete an existing student\n");
printf("5-Find an existing student\n");
printf("6-Quit\n");
printf("====> Choice? ");
scanf("%d", &choice);
switch(choice){
case 1:
LoadStudentsFromDatabase();
printf("Students loaded from database successfully\n");
break;
case 2:
PrintExistingStudentsOnTheScreen();
break;
case 3:
printf("\nFirstName: "); scanf("%s", s.firstName);
printf("LastName: "); scanf("%s", s.lastName);
printf("ID: "); scanf("%d", &s.id);
printf("Gpa: "); scanf("%f", &s.gpa);
printf("Department: "); scanf("%d", &s.department);
AddStudent(&s);
printf("1 student added\n");
break;
case 4:
printf("\nID? "); scanf("%d", &id);
if (DeleteStudent(id)){
printf("Student deleted successfully\n");
} else {
printf("Failed to delete the student. Does not exist?\n");
} /* end-else */
break;
case 5:
printf("\nID? "); scanf("%d", &id);
ps = FindStudent(id);
if (ps == NULL){
printf("Student not found\n");
} else {
char *depts[] = {"CS", "EE", "IE", "CE", "ME"};
printf("+--------------------+--------------------+------+------+------+\n");
printf("| FirstName | LastName | ID | GPA | Dept |\n");
printf("+--------------------+--------------------+------+------+------+\n");
printf("|%20s|%20s|%6d|%6.2f|%6s|\n", ps->firstName, ps->lastName, ps->id, ps->gpa, depts[ps->department]);
printf("+--------------------+--------------------+------+------+------+\n");
} //end-else
break;
case 6:
done = 1;
break;
default:
printf("!!!!!!!!!! Invalid choice. Try again :-))\n");
break;
} /* end-switch */
} /* end-while */
你真的应该验证scanf调用的返回值(事实上,在''',例如'if(scanf(“%d”,&choice)!= 1)/ * error * /;' –
pmg
2013-03-16 09:53:45
我无法重现您描述的行为。你能想出一个SSCCE(http://sscce.org/)吗? – NPE 2013-03-16 10:04:10
[您的ideone代码(我的SSCCE)](http://ideone.com/mwzH4f)的行为如预期! – pmg 2013-03-16 10:23:07