为什么我的输入没有被传递到 if 语句中?
Why is my input not being passed into the if statements?
这是我的代码:
#include "game.h"
#define LINEINPUT 30
int loadMainMenu(void);
void playGame()
{
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
char input[LINEINPUT + EXTRA_SPACES];
printInstructions();
while( getchar() != '\n' );
initialiseBoard(board);
while(TRUE)
{
displayBoard(board, NULL);
printf("At this stage of the program, only two commands are acceptable:\n");
printf("load <g>\n");
printf("quit\n");
fgets(input, LINEINPUT , stdin);
if(input[strlen(input) - 1] != '\n')
{
printf("BUFFER OVERFLOW\n");
readRestOfLine();
EXIT_FAILURE;
continue;
}
if(strcmp(input, "test") == 0)
{
printf("success!\n");
continue;
}
if(strcmp(input, "load 1") == 0)
{
printf("lfdsfsdfoad");
loadBoard(board, BOARD_1);
continue;
}
if(strcmp(input, "load 2") == 0)
{
loadBoard(board, BOARD_2);
continue;
}
if(strcmp(input, "quit") == 0)
{
loadMainMenu();
break;
}
}
}
我已经把它剪掉了,以免占用太多空间space。今天早上我正在编辑其中的一些内容,试图解决问题,但不知何故,它不再读取我的输入。好吧,它确实读取了我的输入,但不使用 strcmp 检查输入是否匹配和 运行 if 语句中的函数。之前用的很好,但是我没怎么改。
如您的第一个 if
语句所示,fgets()
returns 字符串以 \n
行结尾。您需要删除该字符,或将其添加到您要测试的字符串中。
这是我的代码:
#include "game.h"
#define LINEINPUT 30
int loadMainMenu(void);
void playGame()
{
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
char input[LINEINPUT + EXTRA_SPACES];
printInstructions();
while( getchar() != '\n' );
initialiseBoard(board);
while(TRUE)
{
displayBoard(board, NULL);
printf("At this stage of the program, only two commands are acceptable:\n");
printf("load <g>\n");
printf("quit\n");
fgets(input, LINEINPUT , stdin);
if(input[strlen(input) - 1] != '\n')
{
printf("BUFFER OVERFLOW\n");
readRestOfLine();
EXIT_FAILURE;
continue;
}
if(strcmp(input, "test") == 0)
{
printf("success!\n");
continue;
}
if(strcmp(input, "load 1") == 0)
{
printf("lfdsfsdfoad");
loadBoard(board, BOARD_1);
continue;
}
if(strcmp(input, "load 2") == 0)
{
loadBoard(board, BOARD_2);
continue;
}
if(strcmp(input, "quit") == 0)
{
loadMainMenu();
break;
}
}
}
我已经把它剪掉了,以免占用太多空间space。今天早上我正在编辑其中的一些内容,试图解决问题,但不知何故,它不再读取我的输入。好吧,它确实读取了我的输入,但不使用 strcmp 检查输入是否匹配和 运行 if 语句中的函数。之前用的很好,但是我没怎么改。
如您的第一个 if
语句所示,fgets()
returns 字符串以 \n
行结尾。您需要删除该字符,或将其添加到您要测试的字符串中。