分三步,首先将字符串从文件中读取出来,然后统计,最后输出到屏幕上。代码如下
//
// main.cpp
// 11年第7题
//
// Created by 布布 on 2020/5/10.
// Copyright © 2020 布布. All rights reserved.
//
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct word{
char w[20];
int count;
struct word *next;
};
void getdata(char str[])
{
FILE *fp;
char filename[]="test.txt";
if ((fp=fopen(filename, "r"))==NULL) {
printf("can not open file,program exiting\n");
exit(0);
}
char ch=getc(fp);
int i=0;
while (ch!=EOF) {
str[i++]=ch;
ch=getc(fp);
}
str[i]='\0';
fclose(fp);
}
struct word *caculater(char str[])
{
char word1[20];
int i=0,j=0;
struct word *head;
head = (struct word *)malloc(sizeof(struct word));
head->next=NULL;
for (; str[i]!='\0'; i++) {
if (!((str[i]>='a'&&str[i]<='z')||(str[i]>='A'&&str[i]<='Z'))) {
word1[j]='\0';
struct word *q;
q=(struct word *)malloc(sizeof(struct word));
q->next=NULL;
strcpy(q->w, word1);
struct word *p=head;
while (p->next!=NULL) {
if (strcmp(p->next->w, q->w)==0) {
p->next->count++;
break;
}else{
p=p->next;
}
}
if (p->next==NULL) {
p->next=q;
q->count=1;
}
j=0;
}else{
word1[j++]=str[i];
}
}
return head;
}
void print(struct word *head)
{
struct word *p=head;
while (p->next!=NULL) {
printf("%s:%d\n",p->next->w,p->next->count);
p=p->next;
}
}
int main()
{
char str[1000];
getdata(str);
puts(str);
struct word *head;
head=caculater(str);
print(head);
return 0;
}