PracticeDev/study_clang/c_rpc/dict1.c

88 lines
2.3 KiB
C

/* dict1.c -- main, nextin */
#include <stdio.h>
#include <stdlib.h>
#define MAXWORD 50 /* maximum length of a command or word */
/* ------------------------------------------------------------------
* main -- insert, delete, or lookup words in a dictionary as specified
* ------------------------------------------------------------------ */
int main(int argc, char *argv[])
{
char word[MAXWORD + 1]; /* space to hold word from input line */
char cmd;
int wordlen; /* length of input word */
printf("Please input:\n");
while (1) {
wordlen = nextin(&cmd, word);
if (wordlen < 0) {
exit(0);
}
switch (cmd) {
case 'I': /* 初始化 */
initw();
printf("Dictionary initialized to empty.\n");
break;
case 'i': /* 插入 */
insertw(word);
printf("%s inserted.\n", word);
break;
case 'd': /* 删除 */
if (deletew(word)) {
printf("%s deleted.\n", word);
} else {
printf("%s not found.\n", word);
}
break;
case 'l': /* 查询 */
if (lookupw(word)) {
printf("%s was found.\n", word);
} else {
printf("%s was not found.\n", word);
}
break;
case 'q': /* 退出 */
printf("Program quits.\n");
exit(0);
break;
default: /* 非法输入 */
printf("command %c invalid.\n", cmd);
break;
} /* end of switch */
} /* end of while */
return 0;
} /* end of main */
/* ------------------------------------------------------------------
* nextin -- read a command and(possibly) a word from the next input line
* ------------------------------------------------------------------ */
int nextin(char *cmd, char *word)
{
int i, ch;
ch = getc(stdin);
while (isspace(ch)) {
ch = getc(stdin);
} /* end of while */
if (ch == EOF) {
return (-1);
}
*cmd = (char) ch;
ch = getc(stdin);
while (isspace(ch)) {
ch = getc(stdin);
} /* end of while */
if (ch == EOF) {
return (-1);
}
if (ch == '\n') {
return (0);
}
i = 0;
while (!isspace(ch)) {
if (++i > MAXWORD) {
printf("error: word too long.\n");
exit(1);
}
*word++ = ch;
ch = getc(stdin);
} /* end of while */
*word = '\0';
return i;
} /* end of nextin */