结对编程项目作业4

  1. #include<stdio.h>
  2. #include<string.h>
  3. #include<ctype.h>
  4. void main()
  5. {  
  6. char word[1000][20];   /*定义一个存放单词的二维数组*/
  7. int a[100],b[100];
  8. char t[15];
  9. int count;
  10. char ch;
  11. int i,j,m,k;
  12. FILE *file1,*file2;
  13. file1=fopen("wordin.txt","r");    /* 指针f1用于打开源文件wordin.txt */
  14. fscanf(file1,"%c",&ch);          /* 接收第一个当前文件的字符. */
  15. for(i=0;i<=100;i++) 
  16. {  a[i]=0;       /*第i个单词重复出现的次数*/
  17.      b[i]=i;       /*相当于单词序号*/
  18.  }
  19.  count=-1;
  20.  while(!feof(file1))/* 检测是否到达文件结末尾从而执行循环 */
  21.  {
  22.   strcpy(t,"");      /* 初始化用于临时存储单词的变量t */
  23.   while(isalpha(ch))    /* 循环条件为当前字符是英文字母 */
  24.   {
  25.    ch=tolower(ch);       /* 将得到的字符转换为小写 */
  26.    j=strlen(t);              /* 更新当前单词的长度 */
  27.    t[j]=ch;t[j+1]='';
  28.    fscanf(file1,"%c",&ch);      /* 继续读取下一个字符 */
  29.   }
  30.   m=-1;
  31.   for(i=0;i<=count;i++)
  32.    if(strcmp(word[i],t)==0) 
  33.    {a[i]++;m=1;break;}  /* 检索已经存入的单词,若有与当前单词相同则将其数量a[i]的值+1,同时将是否相同的记号m置为1 */
  34.    if (m==-1)
  35.    {count++;strcpy(word[count],t);a[count]=1;}   /* 若经上面的循环没有与当前单词相同者则将新单词存入word并将其数量置为1 */
  36.   while((!isalpha(ch))&&(!feof(file1))) 
  37.   fscanf(file1,"%c",&ch);    /* 若当前字符并非英文字母也不是文件结尾标志直接跳过,不存储 */
  38. }    /* 单词搜索并统计结束 */
  39.  
  40. for(i=0;i<count;i++)
  41.       for(j=i+1;j<=count;j++)
  42.    if(strcmp(word[b[i]],word[b[j]])>0)
  43.     {
  44.      k=b[i];
  45.      b[i]=b[j];
  46.      b[j]=k;
  47.    }
  48.  file2=fopen("wordout.txt","w");       /* 指针f2用于输出结果文件wordout.txt */
  49.  fprintf(file2,"%dn",count+1);                           /* 以下内空皆为输出 */
  50.   for(i=0;i<=count;i++)
  51.   fprintf(file2,"%s %dn",word[b[i]],a[b[i]]);
  52.   fclose(file1);                                             /* 关闭文件 */
  53.   fclose(file2);
  54. }

posted on 2017-12-15 14:33  ccccryst  阅读(72)  评论(0编辑  收藏  举报