1.头文件和函数声明
#include
#include
#include
#define SIZE 100 //最多可存储单词数
//函数声明
int addword(char p[][20], int n); //插入单词的指针,单词个数——返回单词个数
int findword(char p[][20], int n, char* f); //指针,单词个数,待查找的单词——返回位置
int delword(char p[][20], int n, char* f); //指针,单词个数,待查找的单词——返回单词个数
void display(char p[][20], int n); //指针,单词个数
void menu();
2.主函数
int main()
{
//初始化
char myword[100][20]; //个数100,限长20
char searchword[20];
char choice;
int count = 0; //单词个数
int pos = -1; //单词存在状态
//输入
do
{
menu();
printf("请输入你的选择:");
scanf("%c", &choice);
getchar(); //吞掉空格符
switch (choice)
{
case '1':
count = addword(myword, count);
break;
case '2':
printf("请输入您想查找的单词:");
gets(searchword);
pos = findword(myword, count, searchword); //查找该单词在单词本中的位置
if (pos != -1)
printf("这是第%d个单词~\n",pos+1);
else
printf("该单词不存在,请确认是否添加\n");
break;
case '3':
printf("你想删除哪个单词?\n");
printf("请输入:");
gets(searchword); //经过测试,在gets()里不需要getchar()去吞掉回车【在strcmp里无影响】
count = delword(myword, count, searchword);
break;
case '4':
display(myword,count);
break;
case '0':
choice = 0;
break;
default:
printf("ERROEINPUT#TRYAGAIN#\n");
break;
}
} while (choice);
system("pause");
return 0;
}
3.函数定义
a.findword
int findword(char p[][20], int n, char* f)
{
int i;
int pos = -1;
for (i = 0; i < n; i++)
{
if (!strcmp(p[i], f))
{
pos = i;
break;
}
}
return pos;
}
b.addword
int addword(char p[][20], int n)
{
//初始化
int i, j;
int pos = -1;
char flag = 'y';
char tmp[20]; //临时单词区
//判断单词是否存在并插入
while (flag=='y' || flag=='Y')
{
if (n == SIZE)
{
printf("单词本已满,请及时清理或升级为VIP(暂未拓展该业务\n)");
break;
}
else
{
printf("请输入想添加的单词:");
gets(tmp);
pos = findword(p, n, tmp);
if (pos != -1)
{
printf("单词就在你的本子#");
break;
}
else //如果已经存在单词,排序;否则第一个就是它
{
if (n)
{
for (i = 0; i < n && strcmp(tmp, p[i])>0; i++)
;
for (j = n; j > i; j--) //倒着改会减少很多麻烦
strcpy(p[j], p[j - 1]);
strcpy(p[i], tmp); //记得加上单词,最后会返回
n++;
}
else
{
strcpy(p[0], tmp);
n = 1; //记得加上单词,最后会返回
}
}
printf("再加一个?(y/n)\n");
scanf("%c", &flag);
getchar();
//判断一下
while (flag != 'y' && flag != 'Y' && flag != 'N' && flag != 'n')
{
printf("###ERROR###\n");
printf("###请重新输入###\n");
printf("再加一个?(y/n)\n");
scanf("%c", &flag);
getchar();
}
}
}
return n;
}
c.delword
int delword(char p[][20], int n, char* f)
{
int i;
int pos = -1;
pos = findword(p,n,f);
if (pos == -1)
printf("单词不存在...\n");
else
{
for (i = pos; i < n - 1;i++) //直接覆盖
strcpy(p[i], p[i + 1]);
n -= 1;
printf("删除成功\n");
}
return n;
}
d.display
void display(char p[][20], int n)
{
int i;
if (n)
{
for (i = 0; i < n; i++)
puts(p[i]);
}
else
printf("没词,快去添加#\n");
}
e.menu
void menu()
{
printf("\t------------1.增加单词---------\n");
printf("\t------------2.查询单词---------\n");
printf("\t------------3.删除单词---------\n");
printf("\t------------4.显示单词---------\n");
printf("\t------------0.退出-------------\n");
}