软件工程作业单词统计

今天白天还没想好改怎么写我的代码 下午才想好该怎么写代码,最开始没有想用什么来存储单词,也可以叫字符串,最开始以为只是统计单词个数,就想简单的写点就行,用java俩行就可以解决了,后来想起来还要统计行数,才知道要用到文件,所以我的代码用C语言写的。感觉没有要求的东西最难办,哎..........

不管怎么样都得做。。。。

需求分析:1.统计行数

              2.统计单词个数。但是没有排序。

我的代码有待改进,本来是昨天晚上交作业前写的,我今天晚上改进后提交,我以为只是单词统计而已,我今天晚上改进后提交。

以下是我的代码

#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#define MAX     1000
typedef struct word
{
    char str[30];//二维数组用来储存单词
    int count_word;//记录单词个数
    int flag;//标志是否被去掉了
}Word[MAX];
char str[200];
Word coculate_word;//全局变量存储单词的
void Count_C();//统计行数函数
void Count_W();//统计单词的
void print();//打印界面
int main(){
   int select;//选项
   while(1)
   {
       print();
       scanf("%d",&select);
       switch(select)
       {
           case 1:Count_C();break;
           case 2:Count_W();break;
           case 3:exit(0);
       }
       printf("




");
   }
}
void print()//dos用户界面
{
    printf("*********************************************
");
    printf("**********欢迎进入单词统计系统***************
");
    printf("**********1.统计行数*************************
");
    printf("**********2.统计单词个数*********************
");
    printf("**********3.退出*****************************
");
    printf("**********请选择:");
}
void Count_C()//读文件统计行数
{
    FILE* fp;
    int count_c;//行数
    fp=fopen("word.txt","r+");//打开文件
    if(fp==NULL)
    {
        printf("文件打开失败
");
        exit(0);
    }
    count_c=0;
    while(fgets(str,MAX,fp)!=NULL)//按照行读取文件并判断是否读到文件尾
    {
        count_c++;//记录行数
    }
    printf("文本的行数为%d
",count_c);
    fclose(fp);//关闭文件
}
void Count_W()//统计单词函数
{
    FILE* fp;
    int i;
    int k;
    fp=fopen("word.txt","r+");//打开文件
    if(fp==NULL)
    {
        printf("文件打开失败
");
        exit(0);
    }
    for(i=0;i<MAX;i++)//初始化单词数以及标志变量
    {
        coculate_word[i].count_word=1;
        coculate_word[i].flag=1;
    }
    i=0;
    while(!feof(fp))//读取每个单词并存储
    {
        fscanf(fp,"%s",coculate_word[i].str);
        strlwr(coculate_word[i].str);//将单词的所有大些字母转换成小写字母
        i++;
    }

    k=i;//文件中单词的个数
    for(i=0;i<k;i++)//该循环用来统计单词个数的
    {
        if(coculate_word[i].flag==0)
        {
            continue;
        }
        coculate_word[i].flag=0;
        for(int j=1;j<k;j++)
        {
            if(coculate_word[j].flag==0)
            {
                continue;
            }
            if(strcmp(coculate_word[i].str,coculate_word[j].str)==0)
            {
                coculate_word[i].count_word++;
                coculate_word[j].count_word=0;
                coculate_word[j].flag=0;

            }
        }
    }
    printf("************统计结果**************
");
    for(i=0;i<k;i++)
    {
        if(coculate_word[i].count_word!=0)//去掉同样的单词并将单词打印出以及该单词的个数
        {
            printf("单词%s	个数%d
",coculate_word[i].str,coculate_word[i].count_word);
        }
    }


}


下面是运行结果的截图

原文地址:https://www.cnblogs.com/xueshengliuchang/p/5313154.html