-
problem with getline()
I have a program. In this program after using cin.ignore() the getline() isnt working. why?
Code:
#include <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
cin.ignore();
while(t--)
{
string s;
getline(cin,s);
if(s.substr(0,5)=="miao."&&s.substr(s.size()-5,s.size())=="lala.")
cout<<"OMG>.< I don't know!"<<endl;
else if(s.substr(0,5)=="miao.")
cout<<"Rainbow's"<<endl;
else if(s.substr(s.size()-5,s.size())=="lala.")
cout<<"Freda's"<<endl;
else
cout<<"OMG>.< I don't know!"<<endl;
cin.ignore();
}
}
-
Getline consumes the '\n' that's why an ignore after a getline waits for another '\n' that it can ignore
Kurt
-
Code:
#include <iostream>
using namespace std;
int main()
{
int t;
cin>>t;
cin.ignore();
while(t--)
{
string s;
getline(cin,s);
if(s.substr(0,5)=="miao."&&s.substr(s.size()-5,s.size())=="lala.")
cout<<"OMG>.< I don't know!"<<endl;
else if(s.substr(0,5)=="miao.")
cout<<"Rainbow's"<<endl;
else if(s.substr(s.size()-5,s.size())=="lala.")
cout<<"Freda's"<<endl;
else
cout<<"OMG>.< I don't know!"<<endl;
}
}
Now, after inputting t, if I press enter two times, Its giving an out_of_range. How can I improve that?
-
Check that the string is at least 5 char long before calling substr()
Kurt