首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > C++ >

统计重复单词数,但运行结果不太对,不知道那里错了解决办法

2012-04-01 
统计重复单词数,但运行结果不太对,不知道那里错了例如:如果输入是:how,now now now brown cow cow则输出应

统计重复单词数,但运行结果不太对,不知道那里错了
例如:如果输入是:how,now now now brown cow cow
则输出应是“now”这个单词出现了三次
但程序输出不对
#include <iostream>
#include <string>
using namespace std;

int main()
{
string preWord,currWord;
string repWord;
int currCnt=0,maxCnt=1;
cout<<"Enter some Words(Ctrl+z to end):"<<endl;
while(cin>>currWord)
{
if(currWord==preWord)
++currCnt;
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 no repeated word."<<endl;
return 0;
}

[解决办法]
how,now这个被认为是一个单词了,楼主的程序还是不严谨啊。。。
[解决办法]
底下的可以用用!

C/C++ code
#include <iostream>#include <fstream>#include <string>#include <map>using namespace std;void main(void)              {    ifstream input("d:\\1.txt");    string str;    map<string,int> string_count ;    while(input>>str){                ++string_count[str];    }        map<string,int>::iterator it=string_count.begin();        cout<<"字符串"<<"  "<<"出现次数"<<endl;    while(it!=string_count.end()){            cout<<it->first<<"     "<<it->second<<endl;        it++;    }    input.close();} 

热点排行