跪求三道C语言的编程题解答

2025-01-05 01:35:51
推荐回答(2个)
回答1:

#include
#include
#include
char str[20],ch,*p;
FILE *fp;
typedef struct Rec
{
char str[20];
int num;
struct Rec *next;
}Rec;
Rec head,*pp,*news;

int get_ch()
{
ch='0';
ch=fgetc(fp);
if(ch>='a'&&ch<='z' || ch>='A'&&ch<='Z')return 1;
if(feof(fp))return -1;
return 0;
}
void record()
{
if(head.next==NULL)
{
head.next=(Rec*)malloc(sizeof(Rec));
head.next->next=NULL;
strcpy(head.next->str,str);
head.next->num=1;
}
else
{
pp=&head;
while(pp->next)
{
if(strcmp(pp->next->str,str)==0)
{
pp->next->num++;
return;
}
else
{
if(strcmp(pp->next->str,str)>0)
{
news=(Rec*)malloc(sizeof(Rec));
strcpy(news->str,str);
news->num=1;
news->next=pp->next;
pp->next=news;
return;
}
}
pp=pp->next;
}
news=(Rec*)malloc(sizeof(Rec));
strcpy(news->str,str);
news->num=1;
news->next=NULL;
pp->next=news;
}
}
void savefile()
{
fp=fopen("out.dat","w");
pp=head.next;
while(pp)
{
fprintf(fp,"%s:%d\n",pp->str,pp->num);
pp=pp->next;
}
fclose(fp);
}
void check_words()
{
while(1)
{
printf("input word:");
scanf("%s",str);
pp=head.next;
while(pp)
{
if(strcmp(pp->str,str)==0)
{
printf("%s:%d\n",pp->str,pp->num);
break;
}
pp=pp->next;
}
if(!pp)printf("Not exite!\n");
}
}
int main()
{
p=str;
head.next=NULL;
head.num=0;
if(fp=fopen("chapter.dat","r"))
{
while (!feof(fp))
{
if(get_ch()==1)
*p++=ch;
else
{
while (get_ch()==0);
*p='\0';
p=str;
record();
*p++=ch;
}
}
fclose(fp);
savefile();
check_words();
}
else printf("file is not exite!");
return 0;
}

回答2:

一,需要文件操作(打开创建文件,读入数据,写入数据,关闭)
二,需要字符串操作(匹配,判断单词,比较字符串,拷贝字符串)
三,需要数组或链表操作(排序,插入,等等)