单词排序

 编写一个程序,从一个文件中读入单词(即:以空格分隔的字符串),并对单词进行排序,删除重复出现的单词,然后将结果输出到另一个文件中。
【输入形式】
源文件名和目标文件名在执行时作为程序命令行参数输入,例如若程序名为sort,
源文件名和目标文件名分别为sort.in和sort.out,则命令行为:sort sort.in sort.out。
程序将从当前目录下sort.in文件中读入单词。
【输出形式】
对单词进行排序,删除重复出现的单词,然后将结果输出到文件sort.out中。
【输入样例】
假如sort.in文件内容如下:
rrr sss aaa bbb ccc ddf aaa dd

【输出样例】
sort.out文件内容为:
aaa bbb ccc dd ddf rrr sss
【样例说明】
读入文件sort.in,做适当的排序,并删除重复出现的单词,输出到文件sort.out


#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include <conio.h>

typedef struct word
{
 char words[32];
 int count;
 struct word *next;
}WORD;

/
//对链表中的单词进行排序,采用的是冒泡排序算法

void sort(WORD *head)
{
 char str[32];
 int n;
 WORD *p;
 WORD *p2;
 for (p = head;p != NULL;p = p->next)
  for (p2 = p;p2 != NULL;p2 = p2->next)
  {
   //if (p2->count > p->count)
   if(memcmp(p2->words,p->words,32)<0)
   {
    strcpy(str, p->words);
    n = p->count;
    strcpy(p->words, p2->words);
    p->count = p2->count;
    strcpy(p2->words, str);
    p2->count = n;
   }
  }
  
  
}
int fun(FILE *in, FILE *out)
{
 int yes = 1;
 char ch;
 WORD *head = NULL;
 WORD *p;
 WORD *temp;
 char str[128];
 int i = 0;
 if (!(in && out))
 {
  printf("文件打开或建立失败!");
  getch();
 }
 while (!feof(in))
 {
  memset(str, 0, 32);
  while (!feof(in))
  {
   ch = fgetc(in);
   if (ch != 32 && ch != '\n')
   {
    str[i++] = ch;
    yes = 0;
   }
   else
   {
    if (yes != 1)
    {
     str[i] = '\0';
     i = 0;
     yes = 1;
     break;
    }
   }
  }
  if (strlen(str) >= 2)
  {
   temp = head;
   while (temp != NULL)
   {
    
    if (!(strcmp(temp->words, str)))
    {
     temp->count++;
     break;
    }
    temp = temp->next;
   }
   if (temp == NULL)
   {
    p = (WORD*)malloc(sizeof(WORD));
    p->next = head;
    head = p;
    memset(p->words, 0, 32);
    strcpy(p->words, str);
    p->count = 0;
   }
  }
  
 }
 sort(head);
 while (head != NULL)
 {
  fprintf(out, "%-10s%d\n", head->words, head->count);
  head = head->next;
 }
 return 0;
}

 

main()
{
 FILE *in, *out;
 in = fopen("in.txt", "r");
 out = fopen("out.txt", "w");
 fun(in, out);
 
}

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值