Thread: problem with getline()

  1. #1
    Registered User
    Join Date
    Jan 2013
    Posts
    114

    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();
    
    
    }
    }

  2. #2
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Getline consumes the '\n' that's why an ignore after a getline waits for another '\n' that it can ignore
    Kurt

  3. #3
    Registered User
    Join Date
    Jan 2013
    Posts
    114
    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?

  4. #4
    Registered User
    Join Date
    Aug 2005
    Location
    Austria
    Posts
    1,990
    Check that the string is at least 5 char long before calling substr()
    Kurt

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with getline()
    By Kamikaze in forum C++ Programming
    Replies: 3
    Last Post: 03-14-2011, 05:07 AM
  2. getline() problem
    By mrafcho001 in forum C++ Programming
    Replies: 5
    Last Post: 06-12-2005, 01:16 AM
  3. problem with getline
    By Fallout in forum C++ Programming
    Replies: 4
    Last Post: 06-05-2004, 01:46 PM
  4. getline problem
    By luckyboy23 in forum C++ Programming
    Replies: 5
    Last Post: 04-10-2003, 05:40 AM
  5. cin.getline problem
    By Ivan! in forum C++ Programming
    Replies: 5
    Last Post: 01-16-2003, 09:23 AM