您的位置:首页 > 移动开发 > IOS开发

初学者一起看吧。自己学习中遇到的。已经解决。

2009-06-18 21:04 363 查看
 
//从标准输入读入一系列string对象,寻找连续重复出现的单词
//输出重复次数的最大值,若没有单词重复则输出说明信息
#include<iostream>
#include<string>
#include<cstdlib>
using namespace std;
int main(){
string preWord,currWord;
string repWord;
int currCnt=0,maxCnt=1;
cout<<"Enter some words:"<<endl;
while(cin>>currWord){
if(preWord==currWord)
++currCnt;//1
else{
if(currCnt>maxCnt){
maxCnt=currCnt;
repWord=preWord;
}
currCnt=1;
}
preWord=currWord;
}
if(maxCnt!=1)
cout<<'"'<<repWord<<'"'
<<"repeated for"<<maxCnt
<<"times:"<<endl;
else
cout<<"there is none of...."<<endl;
system("pause");

}
////此程序AAAAAAA级经典。且看  1语句
//如果输入ni ni ta ta ta wo wo wo wo
//联系1语句。输入wo的时候++currCnt一直在循环!根本没机会进行下面的if语句
//也就造成了wo和ta 没有进行比较!所以才会输出错误的结果!!!!!!
最后一次输入是无效的,所以结束循环,
直接退出去,这就导致了不能够对记录进行修改了,这个程序只有在最后一批数据最大的时候才会出问题
//正确代码如下
#include <iostream>
#include <string>
#include <cstdlib>
using namespace std;
int main(){
string preWord,currWord;
string repWord;
int currCnt=0,maxCnt=1;
cout <<"Enter some words:" <<endl;
while(cin>>currWord)
{
++currCnt;
if(preWord!=currWord)
{
if(currCnt>maxCnt)
{
maxCnt=currCnt;
repWord=currWord; /////////////////////
}
currCnt=1;
}

preWord=currWord;
}
if(maxCnt!=1)
cout <<'"' <<repWord <<'"' <<"repeated for" <<maxCnt<<"times:" <<endl;
else
cout <<"there is none of...." <<endl;
system("pause");
}

或者
#include <iostream>
#include<cstdlib>
#include <map>

using namespace std;

int main()
{
map<string,int> m;
string name;
while (cin>>name)
{
m[name]++;
}
int max=-1;
string maxName;
for (map<string,int>::const_iterator it = m.begin(); it != m.end(); it++)
{
if (it->second > max)
{
maxName = it->first;
max = it->second;
}
}
cout<<maxName<<":"<<max<<endl;
system("pause");
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息