My aim was to store the words and its counts in a given string which has some space separations. I used map caching to count the repeated words and the logic seems to be good. However, I really not getting, whats wrong with it. It looks like, program skipping to the end and showing some junk output. here is my code:
#include <iostream>
#include <map>
#include <string>
using namespace std;
int main()
{
int T; cin>>T;
for(auto t=0; t<T; ++t){
string full; // sentance/ string with spaces
getline(cin,full);
map<string, int> Map; // word and its count
string strWords;
strWords.clear();
for (int i = 0; i<full.length(); i++)
{
if (full[i] == ' ')
{
Map[strWords]++;
strWords.clear(); // clear it for next word
}
else
strWords += full[i];// if there is no space, build word!
}
Map[strWords]++; // for the last word in the string
for(auto &it: Map)
cout<<it.first<<" "<<it.second<<endl;
}
return 0;
}
Example: for the input
1
yoy yoy koy koy
I am getting an output:
1
instead of
yoy 2
koy 2