單詞出現統計程式

來源:互聯網
上載者:User

//一個根據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;
}

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.