【发布时间】:2016-03-30 04:24:58
【问题描述】:
当我编译我的代码时,程序下面的两个连接函数不能正常工作。当我在我的电脑上编译代码时,一旦我加载其中一个板并返回主菜单选项 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);
}
【问题讨论】:
-
尝试在 main 末尾添加
return 0以消除警告 -
显示
validateNumber的代码 -
int validateNumber() { char line[LINE_LEN + EXTRA_SPACES]; char *end; int input; do { printf("Please enter your choice:"); fgets(line, LINE_LEN + EXTRA_SPACES, stdin); if (line[strlen(line) - 1] != '\n') { readRestOfLine(); continue; } line[strlen(line) - 1] = 0; input = strtol(line, &end, 0); } while(*end); return input; } -
'Welcome' 消息和以下行应该清楚地放在单独的函数中以避免重复。您可能应该使用
else if (choice == 2)和else if (choice == 3)以避免选择1 和2 从showMenu()内部重新输入showMenu()(递归调用)。在playGame()中,不清楚为什么在用户要求退出时重新显示菜单;您可能对playGame()的(递归)调用也有问题。您可能也应该在这里使用else if。你需要重新考虑你的代码以避免递归。
标签: c