建立一个链式存储的线性表存储无名学生信息,每个数据元素包含一个同学的姓名,学号成绩百分制
#include <stdio.h>
#include <stdlib.h> /* has the malloc prototype */
#include <string.h> /* has the strcpy prototype */
#define TSIZE 45 /* size of array to hold title */
struct film {
char title[TSIZE];
int stu;
int rating;
struct film * next; /* points to next struct in list */
};
char * s_gets(char * st, int n);
int main(void)
{
struct film * head = NULL;
struct film * prev, * current;
char input[TSIZE];
/* Gather and store information */
puts("Enter student:");
while (s_gets(input, TSIZE) != NULL && input[0] != '\0')
{
current = (struct film *) malloc(sizeof(struct film));
if (head == NULL) /* first structure */
head = current;
else /* subsequent structures */
prev->next = current;
current->next = NULL;
strcpy(current->title, input);
puts("Enter your 学号 <0-100>:");
scanf("%d", ¤t->rating);
puts("Enter your 成绩 <0-100>:");
scanf("%d", ¤t->stu);
while(getchar() != '\n')
continue;
puts("Enter next student");
prev = current;
}
/* Show list of movies */
if (head == NULL)
printf("No data entered. ");
else
printf ("Here is the list:\n");
current = head;
while (current != NULL)
{
printf("name: %s stu: %d\n score :%d\n",
current->title, current->rating,current->stu);
current = current->next;
}
/* Program done, so free allocated memory */
current = head;
while (current != NULL)
{
free(current);
current = current->next;
}
printf("Bye!\n");
return 0;
}
char * s_gets(char * st, int n)
{
char * ret_val;
char * find;
ret_val = fgets(st, n, stdin);
if (ret_val)
{
find = strchr(st, '\n'); // look for newline
if (find) // if the address is not NULL,
*find = '\0'; // place a null character there
else
while (getchar() != '\n')
continue; // dispose of rest of line
}
return ret_val;
}
你碰到什么问题了呢?
这个数据结构和你说的 每个数据元素包含一个同学的姓名,学号成绩百分制 完全不搭界啊
//建立一个链式存储的线性表存储无名学生信息,每个数据元素包含一个同学的姓名,学号成绩百分制
#include <iostream>
#include <string>
using namespace std;
typedef struct _student
{
string name;
int num;
int score;
_student *next;
}stunode,*stulist;
int main()
{
stulist head = new stunode;
head->next = NULL;
stulist p = head;
for(int i=0;i<5;i++)
{
stulist q = new stunode;
cout<<"输入第"<<i+1<<"名学生的姓名、学号和成绩:"<<endl;
cin>>q->name>>q->num>>q->score;
p->next = q;
p = q;
}
return 0;
}
if (head == NULL) /* first structure */
head = current;
这里需要设置一下prev
if (head == NULL) /* first structure */
{
head = current;
prev = head; //添加这一句
}
else /* subsequent structures */
prev->next = current;
另外,
while(getchar() != '\n')
continue;
这里应该达不到你的目的,你不输入回车的话,scanf不会刷新缓存的,输入回车的话,就continue死循环了