为什么这个cin不能正常工作?

时间:2014-09-25 14:54:16

标签: c++ cin

#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;
}

所以,我制作了这个首先要求测试用例的代码,然后询问字符串的数量,然后对字符串进行排序并输出它们的频率。 现在,在此代码中,只要在输入字符串数后按Enter键,就会显示消息New Inserted,这意味着新行将作为字符串放入地图中。为什么会这样?

谢谢!

PS:我尝试在getline之前添加fflush(stdin),但它也没有帮助。

1 个答案:

答案 0 :(得分:1)

scanf从输入中读取数字,并留下换行符。该换行符由下一个getline解释,并且您最初会得到一个空行。

修复1: 使用scanf阅读换行符:

而不是仅读取数字:

scanf("%d", &t);

使用以下吞下换行符:

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

无论如何,将stdioiostream混合是一个坏主意,但如果您使用

,您会得到类似的相同结果
cin >> t;

修复2 (也适用于流):忽略getline读取的第一行


修复3

使用getline将数字输入字符串并解析它们:

getline(cin, s);
istringstream ( s ) >> t; 
相关问题