📄 phonelst.cpp
字号:
//这个程序在本书所带软盘中。文件名为PHONELST.CPP
//这个程序利用动态链表建立电话号码表,并对其进行查询。
#include <iostream.h>
#include <stdio.h>
#include <conio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
struct phone_strc {
char name[30];
char phone[15];
char address[40];
char city[15];
char state[15];
phone_strc *next;
};
void main(void)
{
void get_data(phone_strc *); //输入数据子程序
void search_display(char *, phone_strc *); //查询并显示结果子程序
char name[30];
char choice;
phone_strc *list, *current, *last; //定义三个结构指针
list = current = new phone_strc; //分配一个节点,并使list指向这个结构
last = list; //使指针last也指向这个节点
while(1)
{
get_data(last); //调用输入子程序
cout << "想继续输入下一个电话号码吗? (y/n): ";
choice = getche();
if(toupper(choice) == 'N')
break;
last->next = new phone_strc; //执行动态链接
last = last->next;
}
last->next = NULL; //将最后一个节点的指针指向NULL
cout << endl << "现在利用人名来查询电话号码" << endl << endl;
while(1)
{
cout << "请输入人名: ";
gets(name);
search_display(name, list); //调用查询并显示结果子程序
cout << endl << "你想继续查询吗? (y/n): ";
choice = getche();
cout << endl;
if(toupper(choice) == 'N')
exit(1);
}
}
/************* 子程序 get_data() *********************/
void get_data(phone_strc *node)
{
cout << "请输入人名: ";
gets(node->name);
cout << "请输入电话号码: ";
gets(node->phone);
cout << "请输入门牌和街名: ";
gets(node->address);
cout << "请输入城市: ";
gets(node->city);
cout << "请输入省份: ";
gets(node->state);
cout << endl;
}
/**************** 子程序 search_display() **********************/
void search_display(char *who, phone_strc *node)
{
int found = 0;
while (node != NULL)
{
if (strcmp(who, node->name) == 0) //如果相等,则找到了这个人的记录
{
cout << endl << "查询结果: " << endl;
cout << node->name << endl;
cout << node->phone << endl;
cout << node->address << endl;
cout << node->city << ", " << node->state << endl;
found = 1;
break; //终止循环
}
node = node->next;
}
if (!found) //如果没有找到
cout << "对不起。这个人不在记录中。" << endl;
}
/*下面是这个程序运行后的一个典型输出结果:
请输入人名: 王钢
请输入电话号码: 626-8900
请输入门牌和街名: 东大街 123 号
请输入城市: 北京
请输入省份: 北京
想继续输入下一个电话号码吗? (y/n): y
请输入人名: 刘维
请输入电话号码: 677-8899
请输入门牌和街名: 西大街 688 号
请输入城市: 石家庄
请输入省份: 河北
想继续输入下一个电话号码吗? (y/n): n
现在利用人名来查询电话号码
请输入人名: 刘维
查询结果:
刘维
677-8899
西大街 688 号
石家庄, 河北
你想继续查询吗? (y/n): y
请输入人名: 张三
对不起。这个人不在记录中。
你想继续查询吗? (y/n): n
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -