#include <iostream>
#include <map>
#include <string>
using namespace std;
int main (void)
{
int c;
cout<<"enter number of test cases\n";
cin>>c;
while (c!=0)
{
string s;
int t;
cout<<"enter number of strings to be entered\n";
cin>>t;
map <string,int> a;
map <string,int>::iterator it;
while ( t!= 0 )
{
getline(cin,s);
it = a.find(s);
if ( it == a.end() )
{
a.insert(pair<string,int>(s,1));
cout<<"New inserted\n";
}
else
{
a[s]++;
cout<<"Value incremented\n";
}
t--;
}
it = a.begin();
cout<<"Value will print\n";
while ( it != a.end() )
{
cout<<it->first<<" "<<it->second<<"\n";
it++;
}
c--;
}
return 0;
}
So, I made this code which first asks for test cases, and then asks for number of strings and then sorts the strings and outputs their frequency.
Now, in this code, as soon as I hit enter after entering the number of strings, the message New Inserted
is displayed, meaning that the new line is being put as a string in the map. Why is that happening?
Thanks!
PS: I tried putting fflush(stdin)
before getline but it doesnt help either.