I have this function:

void read(){
    int id;
    string desc;
    string title, type;
    cout<<"Movie's id: ";
    cin>>id;
    cout<<"Movie's title: ";
    cin>>title;
    cout<<"Movie's description: ";
    getline(cin, desc, '\n');
    cout<<"Movie's type: ";
    cin>>type;
    cout<<"You have typed in: "
        <<id
        <<" "
        <<title
        <<" "
        <<desc
        <<" "
        <<type
        <<".\n";
}

and my problem is that in the desc field, when I must insert something, it skips over, passing to the type field, not letting me insert anything. I've tried in another project only with the getline(cin, desc, '\n') and it worked, it took all the line, but here it just skips the field. My question is this: why does this thing happens? and did I do something wrong?
10x.

Recommended Answers

All 2 Replies

Sounds like another thread of the perils of mixing cin and getline. See this thread.

http://www.daniweb.com/software-development/cpp/threads/90228/flushing-the-input-stream

After line 8, there's an extra '\n' in the input stream. Line 10 gobbles that up and doesn't pause. Whenever you use getline immediately after cin with the >> operator, you need to get rid of thyat extra '\n' in the cin stream. See the ignore command here.

http://www.cplusplus.com/reference/iostream/istream/ignore/

Stick this line right after line 8.

cin.ignore(256, '\n'); // 256 is just a big number.  Gobbles  up the rest of the line so that when you get to getline, you'll pause for input
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.