資源簡介
首先,逐行讀取指定文件中的數據,并進行解析后保存在順序表中。其中,文件中每行數據格式為“學號,姓名,年齡”,比如“SA10225048,[yyw1] 張三,24”。
(提示:采用順序表結構時,順序表中每個表元素包含三類信息:學號,姓名,和年齡;采用單鏈表結構時,單鏈表中每個結點的數據域包含三類信息:學號,姓名,和年齡。)
再,根據鍵盤輸入進行相關操作(查找,刪除和插入)。比如,若鍵盤輸入為“P3”,則表示打印出第3項的信息(注意:采用順序表結構時,第3項數據對應下標為2的表元素;采用單鏈表結構時,第3項數據對應鏈表中第3個結點的信息;);若鍵盤輸入為“D3”,則表示刪除第3個表元素;若鍵盤輸入為“I3,SA10225038,張四,24”,則表示在第3項前插入一個學生的信息(SA10225038,張四,24)。
代碼片段和文件信息
//?Test1.cpp:?定義控制臺應用程序的入口點。
#include?“string.h“
#include?
#include?
struct?student
{
char?id[12];
char?name[10];
int?age;
};
int?main()
{
FILE?*fw?=?fopen(“Lab1test.DAT“?“r“);
int?len?=?0;
student?*list?=?(student*)malloc(sizeof(student)*10);
char?buffer[1000];
//?從文件中讀入一行數據
if?(fw?==?NULL)
{
fprintf(stderr?“Cannot?open/find?the?file!“);
exit(EXIT_FAILURE);
}
while?(!feof(fw))
{
if?(fgets(buffer?1000?fw)?==?NULL)
break;
buffer[strlen(buffer)?-?1]?=?‘\0‘;
char?*result?=?NULL*ptr;
student?aStu;
ptr?=?buffer;
result?=?strtok(ptr?““);
strncpy(aStu.id?result?strlen(result)?+?1);
ptr?=?NULL;
result?=?strtok(ptr?““);
strncpy(aStu.name?result?strlen(result)?+?1);
ptr?=?NULL;
result?=?strtok(ptr?“\0“);
aStu.age?=?atoi(result);
len++;
if(len%10==0)
{
realloc(list?sizeof(student)*(len/10+1)*10);
}
list[len?-?1]?=?aStu;
//printf(“%s\n“?list[len?-?1].id);
}
printf(“打印全部:\n“);
for?(int?i?=?0;?i? printf(“第%d項:學號%s姓名%s年齡%d\n“?i?+?1?list[i].id?list[i].name?list[i].age);
}
printf(“數據讀取完畢,請輸入命令,輸入q退出:\n“);
//?對順序表操作
char?command[200];
gets_s(command);
while?(strcmp(command?“q“))?{
評論
共有 條評論