现在的位置: 首页 > 综合 > 正文

单词出现统计程序

2012年10月03日 ⁄ 综合 ⁄ 共 1494字 ⁄ 字号 评论关闭

//一个根据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;
}

 

抱歉!评论已关闭.