#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct student
{
char id[25];
char name[25];
int chengji1;
int chengji2;
int chengji3;
}stu;
typedef struct tagNode
{
stu date;
struct tagNode *next;
}Node;
Node *head=NULL;
void input()//录
{
Node* NewNode=(Node*)malloc(sizeof(Node));//建立一个结点(人),分配其内存
NewNode->next=NULL;//指针下一个指向空
Node* p=head;
scanf("%s %s %d %d %d",NewNode->date.id,NewNode->date.name,&NewNode->date.chengji1,&NewNode->date.chengji2,&NewNode->date.chengji3);
while(head!=NULL&&p->next!=NULL)
{
p=p->next;
}
if(head==NULL)
{
head->next=NewNode;
}
else
{
p->next=NewNode;
}
}
void search()
{
char num[25];
scanf("%s",num);
Node* p=head;
while(p!=NULL)
{
if(strcmp(p->date.id,num)==0)
{
printf("%s %s %d %d %d",p->date.id,p->date.name,p->date.chengji1,p->date.chengji2,p->date.chengji3);
p=NULL;
}
else if(p->next!=NULL)
{
p=p->next;
}
else
{
printf("Not Found");
}
}
}
int main()
{
int n,i;
scanf("%d",&n);
for(i=0;i<n;i++)
{
input();
}
search();
}
给你找到问题了。
问题1:由输入缓冲区引发的输入报错问题。每次输入前清空输入缓冲区即可。
问题2:scanf("%s %s %d %d %d",NewNode->date.id,NewNode->date.name,&NewNode->date.chengji1,&NewNode->date.chengji2,&NewNode->date.chengji3); 不建议像你这样连着输入,建议分开一个一个的输入。
问题3:当头等于NULL时,应该将该节点赋值给头,而不是赋值给头的下一个
if(head==NULL)
{
//head->next=NewNode;
head = NewNode; // 当头等于NULL时,应该将该节点赋值给头,而不是赋值给头的下一个。
}
除以清空输入缓冲区即可。
下面是我给你改好的代码:
#include <stdio.h>
#include <stdlib.h>
#include<string.h>
typedef struct student {
char id[25];
char name[25];
int chengji1;
int chengji2;
int chengji3;
}stu;
typedef struct tagNode {
stu date;
struct tagNode *next;
}Node;
Node *head = NULL;
void input()//录
{
char c; // 清空输入缓冲区
while ((c = getchar()) != '\n');
Node* NewNode = (Node*)malloc(sizeof(Node));//建立一个结点(人),分配其内存
NewNode->next = NULL;//指针下一个指向空
Node* p = head;
//scanf_s("%s %s %d %d %d", NewNode->date.id, NewNode->date.name, &NewNode->date.chengji1, &NewNode->date.chengji2, &NewNode->date.chengji3);
printf("请输入id:");
scanf_s("%s", NewNode->date.id, 25);
printf("请输入name:");
scanf_s("%s", NewNode->date.name, 25);
printf("请输入成绩1:");
scanf_s("%d", &NewNode->date.chengji1);
printf("请输入成绩2:");
scanf_s("%d", &NewNode->date.chengji2);
printf("请输入成绩3:");
scanf_s("%d", &NewNode->date.chengji3);
while (head != NULL && p->next != NULL) {
p = p->next;
}
if (head == NULL) {
//head->next = NewNode; // BUG
head = NewNode;
} else {
p->next = NewNode;
}
}
void search() {
char c;
while ((c = getchar()) != '\n');
char num[25];
printf("请输入id:");
scanf_s("%s", num, 25);
Node* p = head;
while (p != NULL) {
if (strcmp(p->date.id, num) == 0) {
printf("%s %s %d %d %d", p->date.id, p->date.name, p->date.chengji1, p->date.chengji2, p->date.chengji3);
p = NULL;
}
else if (p->next != NULL) {
p = p->next;
}
else {
printf("Not Found");
}
}
}
int main() {
int n, i;
printf("请输入个数:");
scanf_s("%d", &n);
for (i = 0; i < n; i++) {
input();
}
search();
}