【发布时间】:2014-11-20 09:51:28
【问题描述】:
#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:我尝试将fflush(stdin) 放在 getline 之前,但它也没有帮助。
【问题讨论】:
-
不要将
stdio与iostreams混用。 -
我删除了
stdio.h并使用cin代替scanf(我这样做只是为了让它工作)但它仍然没有。 -
这不是答案,只是一般建议。
-
下次请准备MCVE。整个问题可以用一个 10 行的程序来概括。