C语言编写通讯录怎么按姓名查找联系人?

Python0105

C语言编写通讯录怎么按姓名查找联系人?,第1张

#include <stdio.h>

#include <stdlib.h>

#include <string.h>

#define N 50

struct friend_list {

char name[16]

char tel[16]

char email[20]

}fri[N]

/*void initstu(struct friend_list *p)*/

void add_friend(struct friend_list *p)

void search_friend(struct friend_list *p)

void del_friend(struct friend_list *p,char *name)

void renew_friend(struct friend_list *p,char *name)

int n = 0 // 全局变量,用来记录现有人数

void main(void) {

int friendnumber = 0

int chose = 0

while(1) {

printf("1: 新增联系人\n")

printf("2: 按姓名查找联系人\n")

printf("3: 按姓名删除联系人\n")

printf("4: 按姓名修改联系人\n")

printf("0: 退出\n")

printf("\n 请选择输入(0 - 4):")

scanf("%d",&chose)

switch (chose) {

case 1:add_friend(fri)break

case 2:

case 3:

case 4:

case 0:

default:return

}

}

}

void add_friend(struct friend_list *p) {

if(n >= N) {

printf("已经满员,不能添加了。\n")

return

}

printf("请输入新增联系人的姓名,联系电话,电子邮箱:\n")

scanf("%s%s%s",p[n].name,p[n].tel,p[n].email)

++n

}

void search_friend(struct friend_list *p) {

    int i,flag = 1

char name[16]

printf("请输入要查找的联系人的名字:\n")

scanf("%s",name)

for(i = 0i < n && flagi++) {

if(strcmp(p[i].name,name) == 0) {

printf("%s %s %s\n",name,p[i].tel,p[i].email)

flag = 0

}

}

if(flag) printf("没有找到名字叫:%s的人!\n",name)

}

printf("输入要查询的学生姓名或学号:")

if(!strcmp(stu[i].name,str)) 

改成

if(!strcmp(stu[i].name,str)||!strcmp(stu[i].no,str))//no学号

1 size_t 是无符号整数,你程序里的逻辑是在搜索时坐标会变负数,所以把size_t改成int型

2. 你搜索的是按字母排序的表,所以最好将“hm”排在“wgp”前

下面的程序可以运行:

#include <stdio.h>

#include <string.h>

#include <stdlib.h>

#define _CRT_SECURE_NO_WARNINGS

typedef struct StuInfo

{

int id

char name[100]

}Info

int binarySearchName(Info b[], char searchKey[], int low, int high)

int main()

{

Info stu[3] = { { 0,"hm"},{1,"wgp"} ,{2,"wj"} }

char a[100]

gets_s(a)

int i

i=binarySearchName(stu, a, 0, 1)

if (i!= -1)

printf("find")

system("pause")

return 0

}

int binarySearchName(Info b[], char searchKey[], int low, int high)

{

while (low <= high) {

int middle = (low + high) / 2

if (strcmp(searchKey, b[middle].name) == 0) {

return middle

}

else if (strcmp(searchKey, b[middle].name) <0) {

high = middle - 1

}

else {

low = middle + 1

}

}

return -1

}