利用List统计文件中单词个数,并排序输出

#pragma warning(disable:4786)

#include <iostream>
#include <fstream>
#include <string>
#include <cctype>
#include <list>
#include <iomanip>
#include <algorithm>
#include <iterator>
using namespace std;

void get_word(istream& in_stream,string& w);
void insert_word(string word,list<string>&wordlist);
void display_list(ostream & out_stream,list<string>wordlist);

void main(){
ifstream in_stream;
ofstream out_stream;

string infile,outfile;//filenames
string word;          //string to hold current word

//Prompt for filenames and open files
cout <<"Enter the name of the input file:";
cin>> infile;
cout <<"Enter the name of the output file:";
cin>> outfile;

in_stream.open(infile.c_str());
if (in_stream.fail()) {
cout <<"fail to open this file" << infile <<endl;
}
else{
out_stream.open(outfile.c_str());
list<string> wordlist;
list<string>::iterator iter;
get_word(in_stream,word);    //get a word

//while non-empty word was returned.
while (word.size()) {
insert_word(word,wordlist);
get_word(in_stream,word); //get another word
}
wordlist.sort();
out_stream << "There are " << wordlist.size() << " distinct words.\n";
out_stream <<"\nHere is the ordered list of words\n";
display_list(out_stream,wordlist);
}//end esle

}

/*-----------------------------------------------------------*/

/*-----------------------------------------------------------*/
/*这个函数把一个单词不再单词表中则插入到单词列表中           */

void insert_word(string word,list<string>&wordlist){
list<string>::iterator iter;

iter=find(wordlist.begin(),wordlist.end(),word);
if(iter== wordlist.end()){
//Word is not in list. Insert word.
wordlist.insert(iter,word);
}
}

/*----------------------------------------------------------*/
/*得到输入流中的下个单词,忽视所有非字母的字符              */
void get_word(istream& in_stream,string& w){
char ch;
w = "";        //clear word

in_stream.get(ch);
while (!isalpha(ch)&&!in_stream.eof()) {//skip non-alpha
in_stream.get(ch);
}

while (isalpha(ch)&&!in_stream.eof()) {//read and store alpha
ch = tolower(ch);  //把大写字母改为小写
w +=ch;
in_stream.get(ch);
}
}

/*-----------------------------------------------------------*/
/*把列表中的单词输出到输出流中,每行三个                     */
void display_list(ostream& out_stream,list<string>wordlist){
int columns(3),counter(0);
list<string>::iterator iter;
out_stream<<setiosflags(ios::left);

iter = wordlist.begin();
while (iter!=wordlist.end()) { //循环访问list
out_stream<<setw(20)<<(*iter).c_str();
iter++;
counter++;
if (counter%columns == 0) { //定制列数
out_stream <<endl;
}
}
}

转载于:https://www.cnblogs.com/aquar/archive/2009/08/10/3451526.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值