<分区>
这篇文章有点长,请耐心等待。我想要做的事情的要点是在循环开始时获得一些用户输入,根据该输入做一些事情并可能重复。够简单吧?这是我的。
void displayMain(Album albums[], int num_albums){
int break_condition = 1;
int user_choice;
//keep looping until we decide to quit
while (break_condition){
user_choice = displayMenu();
switch(user_choice){
case 0 :
return; //does this need to be return 0 or can it just be return (or is it the same thing?)
case 1 :
displayAlbums(albums, num_albums);
break;
case 2 :
printf("display tracks\n");
break;
default :
printf("Invalid choice!\n\n");
break;
}
}
return;
}
函数 displayMenu() 基本上获取一些用户输入并返回一个 int。
int displayMenu(void){
printf("Display Menu\n1. Display all albums\n2. Display the tracks in an album\n0. Return to the mainmenu\nPlease enter the choice:\n");
//grab and return the choice
int choice;
scanf("%d", &choice);
return choice;
}
因此,当我最终运行所有这些代码时,如果我输入一个“错误”选择,即:在 switch 语句中采用默认路径的选择,代码将进入无限循环。重复内容
Display Menu
1. Display all albums
2. Display the tracks in an album
0. Return to the main menu
Please enter the choice:
Invalid choice!
我几乎是 C 语言的新手,所以我相信我知道这是为什么。 user_choice 永远不会被重置,即使显然正在调用函数 displayMenu(因为无限循环输出)
为什么在输入了一次“错误”输入后,displayMenu 不再要求用户输入?是因为它不是整数吗?当我尝试调试并打印出 user_choice 时,它是一个很大的数字,很可能是一个寄存器或类似的东西。
请帮忙,正如我所说,我不擅长 C,所以有经验的 C 程序员可能会伸出援手 :)