I am unable to take integer input after using getline to input the string… i tried cin.ignore() but that is not working . Can you suggest something ?
Taking integer input after getline
#include<iostream>
#include<algorithm>
#include <vector>
#include <string>
using namespace std;
bool compare(pair<string,int>p1,pair<string,int>p2)
{
if(p1.second==p2.second) return p1.first<p2.first;
return p1.second>p2.second;
}
int main() {
vector<pair<string,int>> v;
int x,N;
cin>>x>>N;
cin.get();
while(N>0)
{
string s;
int sal;
getline(cin,s);
cin.ignore(sal,'\n');
cout<<sal;
if(x<=sal)
{
v.push_back(make_pair(s,sal));
}
N--;
}
sort(v.begin(),v.end(),compare);
for(auto i: v)
{
cout<<i.first<<" "<<i.second<<endl;
}
return 0;
}
Hello @raks1234,
Try to use the following statement:
getline(cin,s);
cin.get();
cin>>sal;
instead of:
getline(cin,s);
cin.ignore(sal,’\n’);
Let me know if this works.
Doesn’t seem to work.
Anyway, I figured out that using cin to take string input works in this case, however still have a doubt that why getline() doesn’t work even though we are using cin.get() or cin.ignore()
Hello @raks1234,
The following will surely work:
getline(cin,s,’ ');
cin>>sal;
The reason why what i have suggested previously was not working:
As the string and the integer were separated by a white space not endline character.
And getline reads white space also.
So, s was reading sara 100 as a single string.
Above i have specified the delimiter as white space.
Thus, it will work.
Yes, it worked. Thanks for your help.
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.