6

If I use the following code, getline doesn't take the last input(for last iteration of "for" loop, it simply skips it) -

int main()
{
    int n;
    map<string, set<string> > lst;
    string c,s,c2;

    cin>>n;

    for(int i=0;i<n;i++)
    {
            getline(cin,c); // here it skips the input for last iteration
            stringstream ss;
            ss<<c;

            bool f=1;
            while(ss>>s)
            {
                        if(f)
                        {
                             c2=s;
                             f=0;
                        }
                        else
                             lst[c2].insert(s);           
            }
    }

    for (map<string, set<string> >::const_iterator ci = lst.begin(); ci != lst.end(); ++ci)
    {
                cout<< (*ci).first <<" "<< (*ci).second.size() <<endl;
    }
}

To get rid of it, I put cin.ignore() after getline. Now its taking all the inputs but I'm facing a new issue -

#include<iostream>
#include<string>
#include<map>
#include<set>
#include<sstream>
#include<algorithm>

using namespace std;

int main()
{
    int n;
    map<string, set<string> > lst;
    string c,s,c2;

    cin>>n;

    for(int i=0;i<n;i++)
    {
            getline(cin,c);
            cin.ignore();
            stringstream ss;
            ss<<c;

            bool f=1;
            while(ss>>s)
            {
                        if(f)
                        {
                             c2=s;
                             f=0;
                        }
                        else
                             lst[c2].insert(s);           
            }
    }

    for (map<string, set<string> >::const_iterator ci = lst.begin(); ci != lst.end(); ++ci)
    {
                cout<< (*ci).first <<" "<< (*ci).second.size() <<endl;
    }
}

The new issue is that while taking c2, first character of string gets removed. For example, if I give "England Jane Doe" as input to getline, in c2 I'll get "ngland".

How to get rid of this issue now?

4

4 に答える 4

16

これ:

cin>>n;

番号のみを読み取ります。ストリーム
に末尾を残します。'\n'

への最初の呼び出しgetline()は、'\n'

operator>>と を混ぜて使用しないことが最善std::getline()です。ストリームに改行を残したかどうかについては、非常に注意する必要があります。ユーザーから一度に 1 行ずつ読み取るのが最も簡単だと思います。次に、行を個別に解析します。

 std::string  numnber;
 std::getline(std::cin, number);

 int n;
 std::stringstream numberline(number);
 numberline >> n;
于 2012-04-17T22:17:09.827 に答える
2

あなたcin.ignore()は間違った場所にいます。getlineは末尾\nの改行文字を残しません>>。それを行うのはシンボルです。

あなたがおそらく欲しいのは

cin>>n;
cin.ignore();
于 2012-04-17T22:21:00.803 に答える