所以我试图让我的程序读取一行用空格和逗号分隔的用户输入。然后输入将被解析为结构。这就是我到目前为止所写的内容:
void playerFunction()
{
Cell board[BOARD_HEIGHT][BOARD_WIDTH];
Player player;
Position position;
Direction direction;
char input[LINE + EXTRA_SPACES];
char* tok;
char* firstInput;
char* secondInput;
char* thirdInput;
char* fourthInput;
int secondInputInt;
int thirdInputInt;
char str[10];
char str2[10];
if (fgets(input, LINE + EXTRA_SPACES, stdin) == NULL)
{
printf("ERROR! NO INPUT DATA!\n\n");
EXIT_FAILURE;
readRestOfLine();
}
if(input[strlen(input) - 1] != '\n')
{
printf("BUFFER OVERFLOW!\n\n");
EXIT_FAILURE;
readRestOfLine();
}
tok = strtok(input, " ");
firstInput = strdup(tok);
tok = strtok(NULL, ", ");
secondInput = strdup(tok);
tok = strtok(NULL, ", ");
thirdInput = strdup(tok);
tok = strtok(NULL, "");
fourthInput = strdup(tok);
strcpy(str, secondInput);
secondInputInt = atoi(str);
strcpy(str2, thirdInput);
thirdInputInt = atoi(str2);
printf("%s", firstInput);
printf("%d", secondInputInt);
printf("%d", thirdInputInt);
printf("%s", fourthInput);
if (strcmp(firstInput, "init") == 0)
{
if (secondInputInt >= 0 && secondInputInt <= 9)
{
if (thirdInputInt >= 0 && thirdInputInt <= 9)
{
if (strcmp(fourthInput, "north") == 0 || strcmp(fourthInput, "south") == 0
|| strcmp(fourthInput, "west") == 0 || strcmp(fourthInput, "east") == 0 )
{
if (board[secondInputInt][thirdInputInt] == EMPTY)
{
position.x = secondInputInt;
position.y = thirdInputInt;
if (strcmp(fourthInput, "north") == 0)
{
direction = NORTH;
}
if (strcmp(fourthInput, "south") == 0)
{
direction = SOUTH;
}
if (strcmp(fourthInput, "west") == 0)
{
direction = WEST;
}
if (strcmp(fourthInput, "east") == 0)
{
direction = EAST;
}
printf("success");
}
else if (board[secondInputInt][thirdInputInt] == BLOCKED)
{
printf("Board you are trying to initialise is blocked!\n");
}
}
}
}
else
{
printf("error");
}
}
}
这可能不是最好的方法,但到目前为止这是我唯一想过的事情。但是,我意识到来自这4个输入的数据没有被发送到结构中。我已经在代码周围放置了一些prinf语句,以确保实际上正在读取用户输入并且具有。有人知道更简单的设置方法吗?此外,我有时会出现分段错误。