getline() problem

Okay so, in a program that I was working on, i use the getline(cin,message) function and it completely skips over my getline statement. Please help me to understand why. It has done this before in my other programs too.
1
2
3
4
5
6
7
8
9
10
11
12
        int xChoice = 0;
        int yChoice = 0;
        cout << "Please enter the 'x' coordinate to add: ";
        cin >> xChoice;
        cout << "Please enter the 'y' coordinate to add: ";
        cin >> yChoice;
        cout << "Please enter the description of the point: ";
        string message;
        getline(cin,message);
        mapCoords[xChoice][yChoice] = message;
        cout << xChoice << " " << yChoice << endl;
        cout << mapCoords[xChoice][yChoice];
Using cin>> leaves newlines in the buffer, so getline() then reads an empty string. Try looking up cin.ignore().
Okay so I use cin.get() and then use cin.ignore() on the next line to cancel out the newlines?
You can still use cin>>, just use cin.ignore() to ignore the newlines before you use getline().
do i need to use ignore() after EVERY cin? or just once before the getline?
In this case, just once before the getline(). Each cin>> stops at the first whitespace (usually a '\n'). This leaves the newline in the buffer in your case. cin>> also ignores leading whitespace, so it isn't necessary to ignore the remaining newline. getline() doesn't, so you need to ignore only before doing a getline() and only if there is a left over newline.
Okay thanks a lot!! :)
Topic archived. No new replies allowed.