-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtask_1.cpp
More file actions
98 lines (92 loc) · 2 KB
/
task_1.cpp
File metadata and controls
98 lines (92 loc) · 2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
//相比与原代码变化部分如下:
//将原代码main函数的功能模块化,将计算单词和频率的功能写入一个函数。
//考虑到实用性,增加了按单词频率排序,和写入文本的函数
#include <stdio.h>
#include <string.h>
struct words
{
char word[20];
int count;
};
int countword(FILE *fp ,struct words *word)
{
int i=0,j=0,k=0,flag =0;
char c;
char tmp[]={0};
while ((c= fgetc(fp))!=EOF)
{
if (c!=',' && c!='.' && c!='?' && c!=' ' && c!='\n')
{
tmp[j] =(c>='A'&&c<='Z')?c+32:c; //全转成小写
j++;
}else
{
tmp[j] ='\0';
j=0;
flag = 0;
//判断单词是否已经记录 如果已有则使用率加1
for (k=0;k<i;k++)
{
if ( strcmp(tmp,word[k].word)==0 )
{
word[k].count++;
flag = 1;
break;
}
}
//没有则存入单词结构体数组保存
if (!flag)
{
strcpy(word[i].word,tmp);
word[i].count++;
i++;
}
}
}
return i;
}
//使用率排序
int order(int wordnum,struct words *word)
{
int j,k;
struct words stmp = {0};
for (j=0;j<wordnum;j++)
{
for (k=0;k<wordnum-j-1;k++)
{
if (word[k].count>word[k+1].count)
{
stmp = word[k];
word[k] = word[k+1];
word[k+1] = stmp;
}
}
}
return 0;
}
int write(char *str,FILE *fp )
{
printf("Input the word to test.txt\n");
gets(str);
fwrite(str,strlen(str),1,fp);
fseek(fp,0,SEEK_SET);
return 0;
}
void main()
{
struct words word[200] = {0};
struct words stmp = {0};
int wordnum=0,j=0,k=0,flag =0;
char tmp[20]={0};
char str[]={0};
FILE *fp = NULL;
fp =fopen("test.txt","w+");
write(str,fp);
wordnum=countword(fp,word);
fclose(fp);
order(wordnum,word);
for (k=0;k<wordnum;k++)
{
printf("%s%4d\n",word[k].word,word[k].count);
}
}