using <cin> and <getline> successively makes the computer skip some part of a script

Hi, I'm a korean c++ learner again. I really appreciated your kindly responds to my last question.
Now I'm currently studying data structures by making a simple program that would create two <spaceships> : player, and enemy. I programmed it in the way that the user would be the one to enter each ship's name. But I encountered an odd problem here.

-------------------------
struct spaceship
{
string name;
};
-------------------------

I defined my spaceship structure...

-------------------------
spaceship create()
{
spaceship id;
cout << "Please enter your enemy's name :";
getline(cin, id.name, '\n');
return id;
}

int main()
{
spaceship player;
cout << "Please enter the player's name: ";
cin >> player.name;
spaceship new_enemy = create();
}
-------------------------

and finished up the scripts while defining a new function [create()].
As you can see, the player's name would be typed in through <cin>, and the enemy's name through <getline>.

I noticed that as soon as I typed in the player's name and pressed enter, the program would just skip through create() phase, leaving the enemy's name blank.

Is there anything I've missed?
The stream extractors >> typically leave trailing whitespace (which includes newlines) in the input stream.

But getline also uses newlines to mark the end of an input.

The result of which, >> followed by getline usually results in the getline returning immediately, having just read the trailing newline from the previous input.

Either cleanup the input stream following >>, like so
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include<iostream>
#include<iomanip>
#include<limits>
#include<string>
using namespace std;

int main(void) {
    string buff;
    int foo;
    cout << "Enter the integer" << endl;
    cin >> foo;
    cin.ignore(numeric_limits<streamsize>::max(),'\n');
    cout << "Enter the line" << endl;
    getline(cin,buff);
}


Or read everything using getline(), and if you want to use >> to parse the input, then do so using say a stringstream constructed from the input line.
Topic archived. No new replies allowed.