0

Possible Duplicate:
Is this a bug with getline(), or am I doing something wrong. Right way to use getline()?

I tried to learn this topic on STL lists and Strings. So as an integration, i tried out this program:

#include<iostream>
#include<list>
#include<string>
using namespace std;

int main(){
    list<string> obj1, obj2;
    string obj;
    int n;
    cout<<"Enter the number of elements in string list 1:\t";
    cin>>n;
    cin.clear();
    cout<<"Enter the string:\n";
    for( int i=0; i<n; i++){
        getline(cin, obj);
        cout<<"The string is:\t"<<obj<<" and i is "<<i<<endl;
        obj1.push_back(obj);
    }
    obj1.sort();
    cout<<"The string in sorted order is:\n";
    list<string>::reverse_iterator rit;
    for( rit = obj1.rbegin(); rit != obj1.rend(); rit++)
        cout<<*rit<<endl;
    return 0;
}

I get the following output:

Enter the number of elements in string list 1:  4
Enter the string:
The string is:   and i is 0
goat
The string is:  goat and i is 1
boat
The string is:  boat and i is 2
toad
The string is:  toad and i is 3
The string in sorted order is:
toad
goat
boat

The error in the program is that the first string is a blank one that is automatically inserted into the list. In order to avoid this, i tried using cin.clear() but i am not able to overcome the error. Can anyone please identify the bug and help me with the answer.

Community
  • 1
  • 1
Nivetha
  • 698
  • 5
  • 17

3 Answers3

1

One must take special care when using operator>> and getline in the same program. The operator>> leaves an end-of-line indicator in the input stream, which getline accepts.

Try adding std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n') before the getline.

Robᵩ
  • 163,533
  • 20
  • 239
  • 308
0

cin.clear() doesn't do what you think it does. Look it up. Then follow the advice that you got in Rob's answer.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
0

It's because after you enter the number, the newline is still in the buffer, so the first getline gets that newline. The simplest solution is to use a dummy getline call before the loop.

Some programmer dude
  • 400,186
  • 35
  • 402
  • 621