C ++ primer exercises 5.14

#include <iostream>
#include <string>
#include <vector> 
using namespace std;
int main(){
    string Str;//存入下一个需判断单词
    string Cur;//存入当前单词
    vector<string> Vecstr;
    if(cin>>Cur){
   	  unsigned Ccnt=1;//记录当前单词(连续)出现的次数
	  unsigned tempCnt=0; //用来记录最多次数
	  string tempStr;   //用来记录出现最多次数的单词
	  while (cin>>Str){
	    if(Str==Cur)
	    	++Ccnt;
		else{
		   if(Ccnt>tempCnt){
		       tempCnt=Ccnt;
		        tempStr=Cur;
		   }
		   if(Ccnt==tempCnt){
	    	Vecstr.push_back(Cur);
			tempCnt=Ccnt;	
		   }
    	   Cur=Str;
		   Ccnt=1;
		}
	  }
	    if(Vecstr.end()-Vecstr.begin() == 1)
	    cout<<"The word \"" <<tempStr<<"\" attend "
		    << tempCnt<<" times continually."<<endl;
	    else{
	    	 /* for(auto n:Vecstr)
			    cout<<"The word \"" <<n<<"\" attend "
	     	        << tempCnt<<" times continually."<<endl;
			    //与以下块内程序等效,但以下块内程序运行结果更简洁.*/
		    decltype(Vecstr.end() - Vecstr.begin()) i=1;	
	        cout<<"The words \"";
	        for(auto n:Vecstr){	
	        	if(i<Vecstr.end()-Vecstr.begin()-1){
               cout<<n<<"\" , \"";
			   ++i;continue;		
				}
	            if(i==Vecstr.end()-Vecstr.begin()-1){
                cout<<n<<"\"";
				++i;continue;			
				}
                if(i==Vecstr.end()-Vecstr.begin()){
                      cout<<" and "<<n<<"\" attend "<<tempCnt
					      <<" times continually."<<endl;
              }
		    }
		}
        return 0;
    }
    else{
   	     cout<<"The word like that doesn't exist!"<<endl;
   	     return -1;
    } 
}

 

Released two original articles · won praise 1 · views 33

Guess you like

Origin blog.csdn.net/i_wavelet/article/details/86549837