1
#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.

sarah
  • 247
  • 1
  • 9
  • 19

1 Answers1

1

scanf reads the number from the input, and leaves a newline character behind. That newline is interpreted by the next getline, and you get an empty line at first.

Fix 1: read the newline with scanf:

instead of reading the number only:

scanf("%d", &t);

use the following which swallows the newline as well:

scanf("%d\n", &t);

Anyway, it is a bad idea to mix stdio with iostream but you'd get a similar same result if you would use

cin >> t;

Fix 2 (works with streams as well): Ignore the first line read by getline


Fix 3

Use getline to get the numbers into strings and parse them:

getline(cin, s);
istringstream ( s ) >> t; 
Csq
  • 5,775
  • 6
  • 26
  • 39