在C++中的字符串中查找重复单词时输出错误



你能告诉我为什么在我使用映射跟踪给定字符串中的单词和出现时,1会出现在我的输出中吗?

string x="Hello World Hello World";
//getline(cin,x);
map<string,int> store;
stringstream s(x);
do
{
string y;
s>>y;
if(store.find(y)!=store.end())
{
auto it=store.find(y);
it->second++;
}
else
store.insert(pair<string,int>(y,1));
}while(s);
map<string, int>::iterator itr; //common for all maps
for(itr=store.begin();itr!=store.end();++itr)
cout<<itr->first<<" "<<itr->second<<endl; 

输出:

1
Hello 2
World 2 

我使用y.length((纠正了条件的其他部分>0,现在它似乎工作正常。

相关内容

最新更新