编译代码时,程序下面的两个连接函数无法正常工作。当我在我的电脑上编译代码时,我没有错误,但是一旦我加载其中一个电路板并返回到主菜单选项1-2工作正常但我不能使用第三个选项。换句话说,我不能退出游戏。取而代之的是打印“再见!”并要求我选择一个选项。这只发生在我进入'do while'循环并在那里选择第三个选项时。当我在终端中编译代码时,我会以某种方式获得标题中提供的错误消息。终端中发生相同的错误。任何想法如何解决这个问题?如果需要,我可以提供额外的代码。
第一个:
int main() {
printf("Welcome to Car Board \n");
printf("-------------------- \n");
printf("1. Play game \n");
printf("2. Show student's information \n");
printf("3. Quit \n\n");
showMenu();
}
void showMenu(){
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
int choice = validateNumber();
if(choice == 1){
showCommands();
initialiseBoard(board);
displayBoard(board, NULL);
printf("load <g>\n");
printf("quit\n\n");
playGame();
}
if (choice == 2){
showStudentInformation();
}
if (choice == 3){
printf("Good Bye!\n\n");
}
else showMenu();
}
第二个:
void playGame()
{
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
char str1[] = {"load 1"};
char str2[] = {"load 2"};
char str3[] = {"quit"};
char * choice;
do {
choice = validateString();
if (strcmp(choice, str1) == 0) {
printf("\n");
loadBoard(board, BOARD_1);
displayBoard(board, NULL);
playGame();
}
if(strcmp(choice, str2) == 0){
printf("\n");
loadBoard(board, BOARD_2);
displayBoard(board, NULL);
playGame();
}
if(strcmp(choice, str3) == 0){
printf("\n");
printf("Welcome to Car Board \n");
printf("-------------------- \n");
printf("1. Play game \n");
printf("2. Show student's information \n");
printf("3. Quit \n\n");
showMenu();
}
else {
printf("Invalid input\n\n");
playGame();
}
}
while(strcmp(choice, str1) != 0 && strcmp(choice, str2) != 0 && strcmp(choice, str3) != 0);
}
答案 0 :(得分:0)
尝试在main的末尾添加return 0以消除警告
此外,您应该摆脱所有递归调用。而不是
void showMenu(){
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
int choice = validateNumber();
if(choice == 1){
showCommands();
initialiseBoard(board);
displayBoard(board, NULL);
printf("load <g>\n");
printf("quit\n\n");
playGame();
}
if (choice == 2){
showStudentInformation();
}
if (choice == 3){
printf("Good Bye!\n\n");
}
else showMenu(); // Recursive call
}
尝试
void showMenu(){
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
while(1) { // Loop until choice is 3
int choice = validateNumber();
if(choice == 1){
showCommands();
initialiseBoard(board);
displayBoard(board, NULL);
printf("load <g>\n");
printf("quit\n\n");
playGame();
}
else if (choice == 2){
showStudentInformation();
}
else if (choice == 3){
printf("Good Bye!\n\n");
return; // End the function
}
}
}
同样的想法应该应用于PlayGame
函数来摆脱递归调用。另请勿从ShowMenu
致电PlayGame
- 只需执行return