https://www.jianshu.com/p/5ebae8a62c81
最新的版本已发
就这么个题目,我们的C语言附加题作业,可真是让我发愁啊!!
本身对C语言不太熟悉,而且习惯了python的语法,在来写C代码,非常难受,丢三落四,而且对于编程工具的使用并不是很熟悉。做起来非常吃力,不过有了编程的基础,除了在链表排序的地方,花了不少时间,其他的还好。现在我先写出了最初的版本,所有的操作都在一个main()函数中完成,这显然不合理,所以明天会抽空将整个程序分开,作为多个函数来共同完成结果。
题目:
单词处理
~~~~~~~~~~~
对读入的某个文本文件input.txt中,拆出英文单词,输出一个按字典顺序排列的单词表,结果输出在文本文件output.txt中,每个单词一行,并在单词后输出该单词出现的个数,两个字段之间用逗号分隔。约定单词仅由英文字母组成,单词间由非英文字母分隔,相同单词只输出一个,大小写不区分。
例如文本文件input.txt为:
Hello world.
Hello every one.
Let us go.
则输出文本文件output.txt为:
every,1
go,1
hello,2
let,1
one,1
us,1
world,1
试编一个完整的程序完成该功能。(要求:必须用链表实现,结构体如下)
struct myword
{
int num;
char *word;
struct myword *next;
};
最初的代码:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN sizeof(struct myword)
struct myword
{
int num;
char *word;
struct myword *next; /* 指向下一个节点 */
};
void main()
{
struct myword *head;
head = NULL;
struct myword *tmp, *cur,*nxt;
cur=(struct myword *) malloc(LEN);
head = cur;
int size=0;
char infile_name[]={"word.txt"}, outfile_name[]={"output.txt"};
char ch;
char word[20];
char *t_word;
int i=0,j;
FILE * input, *output;
input = fopen(infile_name, "r");
if (input == NULL)
{
printf("打开文件%s失败\n",infile_name);
exit(0);
}
while (! feof(input))
{
ch = fgetc(input);
if ((ch>=65 && ch <=90) || (ch>=97 && ch <=122))
{
word[i]=ch;
i++;
}
else
{
word[i]='\0';
if (strlen(word) !=0)
{
tmp=(struct myword *) malloc(LEN);
t_word = (char *) malloc(strlen(word));
strcpy(t_word,strlwr(word));
tmp->word = t_word;
tmp->num = 1;
tmp->next=NULL;
printf(tmp->word);
printf("\n");
if (size==0)
{
cur->next = tmp;
cur = tmp;
size++;
}
cur = head->next;
while (cur!=NULL)
{
if (strcmp(tmp->word,cur->word)<0)
{
//小于第一个值 ,因为链表有序,如果比第一个小,那就是最小的
tmp->next = cur;
head->next = tmp;
break;
}
if (strcmp(tmp->word,cur->word)==0)
{
//等于当前值
cur->num++;
break;
}
else if (strcmp(tmp->word,cur->word)>0)
{
//大于当前值
if (cur->next!=NULL)// && (tmp->word,cur->next->word)<0
{
//后面不为空
if (strcmp(tmp->word,cur->next->word)<0)
{
//小于下一个值 ,插入当前节点之后
tmp->next = cur->next;
cur->next = tmp;
break;
}
//大于等于下一个值
cur = cur->next;
}
else
{
//后面为空
cur->next= tmp;
break;
}
}
}
}
i=0;
}
}
//cur->next=NULL;
fclose(input);
output = fopen(outfile_name, "w");
if (input == NULL)
{
printf("打开文件%s失败\n",outfile_name);
exit(0);
}
struct myword *p;
p = head->next;
printf("NOW,print LINK......\n");
// if (head->next != NULL)
// {
do
{
fprintf(output,"%s,%d\n",p->word,p->num);
printf("%s,%d\n",p->word,p->num);
p = p->next;
}while(p!=NULL);
// }
fclose(output);
printf("Done!");
}
今天写这个忘了时间。哈哈哈哈。
最后的输出:

网友评论