采用C或C++编程,对出现的单词次数进行统计,并按照出现次数从低到高排序

2025-03-05 00:45:27
推荐回答(3个)
回答1:

//#include "stdafx.h"//vc++6.0加上这一行.
#include "stdio.h"
#include "ctype.h"
#include "string.h"
struct abc{
int n;
char w[21];
};
void main(void){
struct abc wn[500],t;
int i,j,k,x;
FILE *fp;
if((fp=fopen("intxt.txt","r"))==NULL){
printf("Failed to open the input file...\n");
exit(0);
}
memset((char *)wn,'\0',sizeof(wn));
i=j=0;
while((wn[i].w[j]=getc(fp))!=EOF){
if(isalpha(wn[i].w[j])) j++;
else{
wn[i].w[j]='\0';
for(k=0;k if(!strcmp(wn[i].w,wn[k].w)){
wn[k].n++;
break;
}
if(k>=i && j) wn[i++].n++;
j=0;
}
}
fclose(fp);
for(j=0;j for(x=j,k=j+1;k if(wn[x].n>wn[k].n) x=k;
if(x!=j){
t=wn[j];
wn[j]=wn[x];
wn[x]=t;
}
}
if((fp=fopen("outtxt.txt","w"))==NULL){
printf("Failed to open the output file...\n");
exit(0);
}
for(i=0;i fprintf(fp,"%s\t%d\n",wn[i].w,wn[i].n);
printf("%s\t%d\n",wn[i].w,wn[i].n);
}
fclose(fp);
}

回答2:

#include
#include

int main(int, char*[])
{
std::map words;
std::ifstream in("输入文件");
while (in && !in.eof())
{
std::string word;
in >> word;
++words[word];
}

std::multimap counts;
for (std::map::const_iterator i = words.begin(); i != words.end(); ++i)
counts.insert(std::make_pair(i->second, i->first));

std::ofstream out("输出文件");
for (std::multimap::const_iterator i = counts.begin(); i != counts.end(); ++i)
out << i->second << " " << i->first<< '\n';

return 0;
}

回答3:

路过!帮顶!