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