单词出现统计程序

//一个根据C++ Primer 习题改变的程序,使用方法为在主程序后加要读入的文件作为参数,作用为

//自动按字典顺序输出所有单词及其出现次数,存在的问题同习题10.9及C++ Primer中的例题中读单词

//的问题。

int main(int argc, char *argv[])
{
if(argc!=2)//检查参数数目
{
cerr<<"error:wrong argment number.First was the word,second the file name.";
return -1;
}
ifstream ifile;
ifile.open(argv[1]);
if(!ifile)//检查文件打开情况
{
cerr <<"error:unable to open input file: "<<argv[1]<<endl;
return -1;
}
string line,word;
map<string,int> wordCount;
while(getline(ifile,line))
{
istringstream isstream(line);
while(isstream >>word)//读入每个单词
{
++wordCount[word];
//T10.12的形式就是把上面一句注释掉,把下面的注释去掉,当然是第一种方便
/*pair<map<string,int>::iterator,bool> ret =
wordCount.insert(make_pair(word,1));
if(!ret.second)
++ret.first->second;*/
}
}
ifile.close();
cout<<"the words occor in "<<argv[1]<<endl;
for(map<string,int>::const_iterator mapIt = wordCount.begin();
mapIt != wordCount.end();++mapIt)
{
cout<< mapIt->first<<" occor "<<mapIt->second
<< ( mapIt->second > 1 ? " times" : " time" )<<endl; //输出,最后用一个?:操作来输出正确的复数形式
}
return 0;
}

void printContainer(list<int>::const_iterator first,list<int>::const_iterator last)
{
cout<<endl;
for(;first != last;++first)
{
cout <<*first<<" ";
}
cout<<endl;
}
void printContainer(deque<int>::const_iterator first,deque<int>::const_iterator last)
{
cout<<endl;
for(;first != last;++first)
{
cout <<*first<<" ";
}
cout<<endl;
}
void printContainer(vector<int>::const_iterator first,vector<int>::const_iterator last)
{
cout<<endl;
for(;first != last;++first)
{
cout <<*first<<" ";
}
cout<<endl;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值