這裏是我的代碼,我的陳述是,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