首先定义一个结构体存储单词及单词个数:

typedef struct 
{
    char danci[15];//储存单词
    int count;//记录单词出现次数
}sq;

  

参照之前写过的程序中读入文本文档的代码片段,可写出以下代码来打开一个固定名字的文件:

	sq word[M];
	int K,n=0,i,j;

	FILE *fp;
	char ch;
	//fp=fopen("d://p.txt","r");
	if((fp=fopen("p.txt","r"))==NULL)
	{
		cout<<"无法打开文件!"<<endl;
		exit(0);
	}	

	while(!feof(fp))
        {
        }

 

然后开始读入内容并判断每个单词,且计数,

 

ch=getc(fp);
        if(ch==' '||ch==10)
        {
            continue;
        }
        if((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z'))              
        {
            K=0;
            word[n].count=0;
            while((ch>='a'&&ch<='z')||(ch>='A'&&ch<='Z')||(ch=='\''))
            {
                if(ch>='A'&&ch<='Z')
                    ch+=32;
                word[n].danci[K++]=ch;
                ch=getc(fp);
            }
    //判断单词并全部归成小写
word[n].danci[K++]='\0'; n++; //一个单词结束 for(i=0;i<n;i++) if(strcmp(word[i].danci,word[n-1].danci)==0) { word[i].count++; }
      //与前面单词比较 }

 最后输出:

for(i=0;i<n;i++)
	{
		cout<<word[i].danci<<"  "<<word[i].count<<endl;
	}

这只是实现了输出每个单词及它的次数,并没有排序,可作为我的bata版。

bata版运行后结果如下:

文本内容:

  I heard, that your ,settled down.
  That you, found a girl and your married now.
  I heard that your dreams came true.
  Guess she gave you things, I didn't give to you.
  
  Old friend, why are you so shy?
  It didn't like you to hold back or hide from the lie.
  I hate to turn up out of the blue uninvited.
  But I couldn't stay away, I couldn't fight it.
  I'd hoped you'd see my face & that you'd be reminded,
  That for me, it isn't over.

  

  运行结果:

 

增加排序及改进

 

关于排序,采用了冒泡法,这里有一个好朋友的帮忙,很是惭愧,因为自己水平有限,大部分程序都是参考着写的。

排序并筛选出频率最高的前十个单词的代码如下:

	//排序并输出频率最高的十个单词
sq frequency_max[10]; sq temp; for(i=0;i<10;i++) { frequency_max[i]=word[i];//初始化频率最高的十个单词为前十个单词 } //前十个单词不能相同 int k=0; for(i=0;i<10;i++) for(j=i+1;j<10;j++) { l1: if(!strcmp(frequency_max[i].danci,frequency_max[j].danci)) { frequency_max[j]=word[10+k]; k++; goto l1; } } for(i=0;i<10;i++)//排序 for(j=0;j<10;j++) if(frequency_max[i].count>frequency_max[j].count) { temp=frequency_max[i]; frequency_max[i]=frequency_max[j]; frequency_max[j]=temp; } for(i=10;i<n;i++) l2: { for(int l=0;l<10;l++) { if(!strcmp(frequency_max[l].danci,word[i].danci)) { i++; goto l2; } } if(frequency_max[9].count<word[i].count) { int a=8; while(frequency_max[a].count<word[i].count&&a>=0) { a--; } for(j=9;j>a+1;j--) { frequency_max[j]=frequency_max[j-1]; } if(a<0) frequency_max[0]=word[i]; else frequency_max[j]=word[i]; } }

  

然后改进了读文件的部分,改成了输入文件路径,这样就拓宽了范围,不再死盯一个文件。

代码如下:

sq word[M];
	int K,n=0,i,j;
	char infile[10];
    cout<<"***********请输入文件路径:***********"<<endl;
	cin>>infile;	
	FILE *fp;
	char ch;
	//fp=fopen("d://pro.txt","r");
	if((fp=fopen(infile,"r"))==NULL)
	{
		cout<<"无法打开文件!"<<endl;
		exit(0);
	}	
	while(!feof(fp))
    {
    }

  

这也就是我的程序的最终版了。

调试结果:

文本内容:

HILLARY CLINTON:

  Thank you very much.

  You know, tonight, we are hearing the voices of people across America, people of all ages, of all colors, all faiths and all walks of life, people on the day shift, the night shift, the late shift, with the crying babies, moms and dads who want a better world for our children, young people who deserve a world of opportunity, all those who aren't in the headlines, but have always written America's story.

  After seven years of a president who listens only to the special interests, you're ready for a president who brings your voice, your values and your dreams to your White House.

  And tonight, in record numbers, you voted not just to make history, but to remake America. People in American Samoa, Arkansas, Massachusetts, New Jersey, Oklahoma, Tennessee, and the great state of New York and on just -- on just one really serious note, we want to keep the people of Arkansas and Tennessee in our prayers. They suffered horrible tornadoes tonight.

  We just talked to some of our folks there and people have died in both states, and our thoughts and prayers go out to them in this moment of their need.

  You know, tonight, though, is your note. Tonight is America's night. And it's not -- it's not over yet, because the polls are still open in California for a few more minutes.

  I hope that all of you will join our campaign at www.hillaryclinton.com, because you know -- you know that politics isn't a game. It's not about who's up or who's down.

  It's about your lives, your families, your futures. It's about the people who have shared their problems with me, looking for solutions, the mother whose insurance company won't pay for her child's treatment, the couple so determined to send their daughter to college, they're willing to mortgage their home with a sub-prime second mortgage, the man who asked me what he was supposed to do after training the person who will take his job in another country, the veterans who've come home only to find they don't have the health care, the compensation and the services they need.

  It's also about the people who want to seize America's opportunities. It's about the unions and businesses who are training people for green collar jobs.

  It's about the auto companies and the auto workers who want higher gas mileage cars so we can compete with the rest of the world.

  It's about -- it's about our scientists and researchers who want to be able to do stem cell research right here in the United States of America.

  It's about our contractors and our construction workers who want to get to work to rebuild America, from the bridges in Minnesota to the levees in New Orleans.

  Now, for seven years, we have seen President Bush's answer. They don't know what's at stake in this election, but we do. We know what we need is someone ready on day one to solve our problems and seize those opportunities.

  Because when the bright lights are off and the cameras are gone, who can you count on to listen to you, to stand up for you, to delivery solutions for you?

  Well, the Republicans want eight more years of the same. They see tax cuts for the wealthy and they say, "Why not more?" They see $9 trillion in debt and say, "Why not trillions more?" They see five years in Iraq and say, "Why not 100 more?" Well,they've got until January 20th, 2009 and not one day more.

  Now, we know the Republicans won't give up the White House without a fight. Well, let me be clear -- I won't let anyone swift vote this country's future.

  Together, we're going to take back America, because I see an America where our economy works for everyone, not just those at the top, where prosperity is shared and we create good jobs that stay right here in America.

  I see an America where we stand up to the oil companies and the oil-producing countries, where we launch a clean energy revolution and finally confront the climate crisis.

  I see an America where we don't just provide health care for some people or most people, but for every single man, woman and child, that no one is left out.

  I see -- I see an America where, when a young man or a woman signs up to serve our country, we sign up to serve them, too.

  An America with a 21st century GI Bill of Rights to help veterans go to college, buy a home or start their own businesses.

  see an America respected around the world again that reaches out to our allies and confronts our shared challenges from global terrorism to global warming to global epidemic.

  That's the America I see and that's the America we will build together.

  I am so lucky to have the most extraordinary staff, volunteers and supporters across the country.

  And I am so grateful for all those long hours and late nights that you've been putting in. And I want to thank the most important people in my life.

  First, Bill and Chelsea for their incredible love and support.

  They have done so much day in and day out.

  And I want to thank all my friends and family, particularly my mother, who was born before women could vote and is watching her daughter on this stage tonight.

  I also -- I also -- I also want to congratulate Senator Obama for his victories tonight, and I look forward to continuing our campaign and our debate about how to leave this country better off for the next generation, because that is the work of my life.

  That is why I started my career fighting for abused and neglected children, children who had drawn the short straw in life, because this nation gave me every opportunity, and we can do the same for every child.

  We must continue to be a nation that strives always to give each of our children a better future, a nation of optimists who believe our best days are yet to come, a nation of idealists, holding fast to our deepest values, that we are all created equal, that we all deserve to fulfill our God given potential, that we are destined for progress together.

  It's the ideal inscribed on the base of the Statute of Liberty in this great city that has overlooked our harbor through wars and depression and the dark days of September 11, the words we all know that give voice to America's embrace -- "Give me your tired, your poor, your huddled masses, yearning to breathe free" -- a constant reminder that here in America, we face our challenges and we embrace all of our people.

  So today we say with one voice -- give us the child who wants to learn, give us the people in need of work, give us the veterans who need our care. We say give us this economy to rebuild and this war to end. Give us this nation to heal, this world to lead, this moment to seize.

  I know we're ready.

  Thank you all and God bless you.

  运行结果:

 

经验证,正确。

 

本次程序共耗费大概三天,没有精确地计算确切时间,有朋友的帮忙,总算是成功了,收获不小。