无论您如何处理,您只需按顺序逐步完成,并验证您从用户那里获得的所需init DIRECTION X Y 输入的每个部分。无法使用scanf 系列,这不是问题,您只需要依赖指针和索引算法即可。
在这方面的一种方法是沿着输入字符串向下移动指针,并在进行过程中比较值。有很多方法可以做到这一点,但一种方法如下:
#include <stdio.h>
#include <string.h>
#define MAXC 256
void help() { printf (" format 'init DIRECTION X Y'\n"); }
int main (void) {
enum { EAST, NORTH, WEST, SOUTH } dir;
char *names[] = { "EAST", "NORTH", "WEST", "SOUTH" };
char input[MAXC] = "";
char *init = "init";
int x, y;
for (;;) {
char *p, *ep = NULL;
printf ("Enter the commmand: ");
fgets (input, MAXC, stdin);
if (strncmp (input, init, strlen (init))) { /* compare 'init' 1st */
help(); continue;
}
if (!(p = strchr (input, ' ') + 1)) { /* find 1st space */
help(); continue;
} /* locate 'N', 'S', 'E', 'W' */
while (*p && *p != 'E' && *p != 'N' && *p != 'W' && *p != 'S') p++;
if (!*p || !(ep = strchr (p, ' '))) { /* find following space */
help(); continue;
}
*ep = 0; /* nul-terminate */
switch (*p) { /* test cardinal names */
case 'E' : if (strcmp (p, "EAST")) { help(); continue; }
else dir = EAST;
break;
case 'N' : if (strcmp (p, "NORTH")) { help(); continue; }
else dir = NORTH;
break;
case 'W' : if (strcmp (p, "WEST")) { help(); continue; }
else dir = WEST;
break;
case 'S' : if (strcmp (p, "SOUTH")) { help(); continue; }
else dir = SOUTH;
break;
default : help(); continue;
}
*ep = ' '; /* restore space */
p = ep + 1; /* advance to next char */
while (*p && (*p < '0' || '9' < *p)) p++; /* find digit */
if (!*p) {
help(); continue;
}
x = *p++ - '0'; /* set x value -- single digit conversion */
while (*p && (*p < '0' || '9' < *p)) p++; /* find digit */
if (!*p) {
help(); continue;
}
y = *p - '0'; /* set y value -- single digit conversion */
break; /* made it! break out of loop */
}
printf ("\n direction '%s', x '%d', y '%d'\n\n", names[dir], x, y);
return 0;
}
当您的输入不满足您的要求时,给用户一点help() 提醒他们正确的格式是有帮助的,这样他们就不会无休止地看着闪烁的光标想知道如何解决谜题。
使用/输出示例
$ ./bin/direction
Enter the commmand: dog food
format 'init DIRECTION X Y'
Enter the commmand: inid NORTH 3 6
format 'init DIRECTION X Y'
Enter the commmand: init EASY 4 5
format 'init DIRECTION X Y'
Enter the commmand: init EAST a 6
format 'init DIRECTION X Y'
Enter the commmand: init WEST 6 b
format 'init DIRECTION X Y'
Enter the commmand: init SOUTH 4 8
direction 'SOUTH', x '4', y '8'
您可以添加额外的验证,但这是一个开始。