您好,我是 c 新手,所以我的代码有一些问题。我的代码应该显示一个菜单,如果您想添加、搜索、删除或打印所有内容,该菜单会显示。但是,这有效,我的插入部分无效。当我选择添加并开始输入我希望程序崩溃的信息时?
这是我的代码
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>
#pragma warning(disable: 4996)
//#define max 100
typedef enum { diploma, bachelor, master, doctor } education;
struct person { // a node to hold personal details
char name[30];
char email[30];
int phone;
education degree;
struct person* next;
} *head;
void branching(char c);
int insertion();
struct person *search(char *sname);
void deletion(char *sname);
void print_all();
char *x;
//Main Method
int main() { // print a menu for selection
char ch;
do {
printf("Enter your selection\n");
printf("\ti: insert a new entry\n");
printf("\td: delete an entry\n");
printf("\ts: search an entry\n");
printf("\tp: print all entries\n");
printf("\tq: quit \n");
ch = tolower(getchar());
branching(ch);
} while (ch != 113);
return 0;
}
void branching(char c) { // branch to different tasks
switch (c) {
case 'i':
insertion();
break;
case 's':
printf("Enter an item to search");
scanf("%s", x);
search(x);
break;
case 'd':
printf("Enter an item to delete");
scanf("%s", x);
deletion(x);
break;
case 'p':
print_all();
break;
case 'q':
break;
default:
printf("Invalid input\n");
}
}
//insert entry
int insertion(){
struct person *p;
p = (struct person*)malloc(sizeof(struct person));
if (p == 0){
printf("There are no more places to insert.\n"); return -1;
}
printf("Enter name, email, phone, and degree:\n");
scanf("%s", p->name);
scanf("%d", &p->phone);
scanf("%s", p->email);
scanf("%i", p->degree);
p->next = head;
head = p;
return 0;
}
//search method
struct person *search(char *sname){
struct person *p = head, *b = p;
printf("Please enter the name you wish to search:\n");
scanf("%c", sname);
while (p != 0)
if (strcmp(sname, p->name) == 0){
printf("Phone: %d\n", p->phone);
printf("Email: %s\n", p->email);
printf("Degree: %s\n", p->degree);
return b;
}
else{
b = p;
p = p->next;
}
printf("The name does not exist.\n");
return 0;
}
//delete entry
void deletion(char *sname){
struct person *t, *p;
p = head;
t = head;
while (t != NULL){
if (t->name == sname){
if (t == head){//case 1
head = t->next;
free(t);
return;
}
else{
p->next = t->next;
free(t);
return;
}
}
else{
p = t;
t = t->next;
}
}
return;
}
//print
void print_all(){
struct person *p;
p = head;
if (p = NULL){
printf("No entries found.");
}
else{
while (p != NULL){
printf("%s", p->name);
printf("%d", p->phone);
printf("%s", p->email);
printf("%s", p->degree);
p = p->next;
}
printf("\n");
}
}