以下是簡單菜單的代碼。如果用戶輸入無效選項(4或'o'),應重新打印菜單,顯示錯誤消息。該代碼在用戶輸入數字時起作用,但當用戶向選項中輸入字母或字符串時,該代碼失敗(循環無限期)。我的猜測是在產生奇怪行爲的循環情況下內存被覆蓋。有人可以幫我解決它嗎? 謝謝菜單循環中scanf的奇怪行爲
int inmenu = 1;
while (inmenu){
//Menu
printf("User: %s %s\n", user.firstname, user.lastname);
printf("0) Exit\n1) List Friends\n2) Add Friend\n3) Delete Friend\nWhat would you like to do? ");
int option;
scanf("%i", &option);
if(option == 0)
inmenu = 0;
else if (option == 1)
defaultPrint(friends, numfriends, NULL);
else if (option == 2){
//addfriend
char *name = (char *) malloc(sizeof(char) * 256);
int birthdate;
printf("Enter first name: ");
scanf("%s", name);
printf("Enter last name: ");
scanf("%s", name);
printf("Enter birthdate: ");
scanf("%i", &birthdate);
}
else if (option == 3){
//deletefriend
defaultPrint(friends, numfriends, NULL);
int n;
printf("What friend would you like to delete? ");
scanf("%i", &n);
}
else
printf("ERROR: Invalid option %i\n", option);
}
測試輸入:
0) Exit
1) List Friends
2) Add Friend
3) Delete Friend
What would you like to do? 4
ERROR: Invalid option 4
0) Exit
1) List Friends
2) Add Friend
3) Delete Friend
What would you like to do?
(正確的行爲)
0) Exit
1) List Friends
2) Add Friend
3) Delete Friend
What would you like to do? o
What would you like to do? ERROR: Invalid option 4
0) Exit
1) List Friends
2) Add Friend
3) Delete Friend
...
(不正確的行爲保持打印在一個無限循環相同的最後5行)
檢查此問題。 http://stackoverflow.com/questions/1716013/why-is-scanf-causing-infinite-loop-in-this-code –
你可能想看看答案並接受答案。像我一樣,例如。 – tekknolagi