#include <stdio.h> #include <string.h> #include <stdlib.h> int main() { char input[21]; char command[6][21] = {"reset", "reset board", "board add", "board delete", "reboot backplane", "backplane abort"}; char exec[7][21] = {"reset what", "board fault", "where to add", "no board at all", "impossible", "install first", "unknown command"}; while(fgets(input, sizeof(input), stdin) != NULL){ int len = strlen(input); // printf("len is %d\n", len); if(input[len - 1] == '\n') input[len - 1] = '\0'; len = strlen(input); // printf("len is %d\n", len); char firstword[21], secondword[21]; int oneortwo = 1; int i = 0, j = 0; while(i < len) { // 读取第一个单词 if(oneortwo == 1) { firstword[i] = input[i]; i++; // 如果有空格证明有两个单词 if(input[i] == ' ') { firstword[i] = '\0'; i++; oneortwo = 2; } } else if(oneortwo == 2) { // 如果已经遇到过空格,读取第二个单词 secondword[j++] = input[i++]; } } secondword[j] = '\0'; // printf("%s\n%s\n", firstword, secondword); // 如果只输入一字串 int error = 0; if(oneortwo == 1) { // 只和一个关键字的命令行匹配。 for(int x = 0; x < i; x++) { if(firstword[x] != command[0][x]){ // 如果输入一字串, 但是匹配命令有两个关键字,匹配失败 printf("%s\n", exec[6]); error = 1; } } if(error == 0) { printf("%s\n", exec[0]); } } else if(oneortwo == 2){ // 如果有两个词汇 // 我们先检查第一个单词 int notmatch[6] = {1}; // 分别和每个命令匹配 int firstwordlen = strlen(firstword); // printf("first word's length is %d\n", firstwordlen); for(int x = 1; x < 6; x++) { for(int y = 0; y < firstwordlen && command[x][y] != '\0'; y++) { // printf("字母%c和%c\n",firstword[y],command[x][y]); if(firstword[y] != command[x][y]) { // 遇到不匹配的就标记不匹配 notmatch[x] = 1; // printf("单词%s和%s不匹配\n",firstword,command[x]); break; } } } // 然后检查第二个单词 char *secondwordToken; for(int x = 1; x < 6; x++) { if(notmatch[x] == 0) { char *temp = (char *)malloc(sizeof(char) * 21); // printf("the command is %s\n", command[x]); int spaceindex; for(int a = 0; a < strlen(command[x]); a++) { if(command[x][a] == ' ') spaceindex = a; } strncpy(temp, command[x] + spaceindex + 1, strlen(command[x]) - spaceindex - 1); secondwordToken = temp; // printf("the command is %s\n", command[x]); // printf("temp (seconde word) is %s\n", temp); if(temp != NULL) { for(int y = 0; y < j && secondword[y] != '\0'; y++) { if(secondword[y] != temp[y]) { notmatch[x] = 1; } } } } } // 检查完两个单词之后如果notmatch里面只有一个0的话我们就找到要执行的命令了,如果有多个0或者没有0,则匹配失败 int count = 0; int index = 0; for(int x = 1; x < 6; x++) { count += notmatch[x]; if(notmatch[x] == 0) index = x; } if(count == 4) { printf("%s\n", exec[index]); } else { printf("%s\n", exec[6]); } } } return 0; }