借鉴了这位老哥的思路:地址
#include<stdio.h> #include<string.h> #include <stdlib.h> #define MAX_CHAR 100 void out_tmp(int index); char *cmd1[6] = {"reset", "reset", "board", "board", "reboot", "backplane"}; char *cmd2[6] = {"no use", "board", "add", "delete", "backplane", "abort"}; int main(int argc, char const *argv[]) { char in[MAX_CHAR] = {}; // fgets(in, 100, stdin); while (gets(in)) { int len = strlen(in); if (len == 0) { printf("\r\n"); continue; } int flag = 1, pob = 0;//找到指向两个字空格的地方 //考虑输入一个字还是两个字 for (int i = 0; i < len; i++) { if (in[i] == ' ') { pob = i; flag = 0; break; } } if (flag) { if (strncmp(in, cmd1[0], len) == 0) { printf("reset what\n"); } else { printf("unknown command\n"); } } else { int count=0, ret_flag; //输入的匹配情况,只有唯一的情况下才输出对应命令 for (int i = 1; i < 6; i++) { if (strncmp(in, cmd1[i], pob) == 0 && strncmp(in+pob+1, cmd2[i], len-pob-1) == 0) { ret_flag = i; count++; } } if (count == 1) { out_tmp(ret_flag); } else { printf("unknown command\n"); } } } return 0; } void out_tmp(int index){ switch (index) { case 0: printf("reset what\n"); break; case 1: printf("board fault\n"); break; case 2: printf("where to add\n"); break; case 3: printf("no board at all\n"); break; case 4: printf("impossible\n"); break; case 5: printf("install first\n"); break; default: break; } }