0

Possible Duplicate:
Need help with getline()

I'm trying to use the getline function in conjunction with cin to get input from the keyboard but my code skips over the getline statement and instead proceeds to cin function below. Here is my code and a screenshot of what is happening.

enter image description here

void addmovie(ofstream& MovieContentsFile) {

string movieTitle;
int movieQuantity;

cout << " \n Add Movie Selected \n " << endl;

cout << "Please type in the movie title and press enter \n" << endl;

getline(cin,movieTitle, '\n');

cout << "Movie: " << movieTitle << "Please type in the amount of copies we have of this movie \n " << endl;

cin >> movieQuantity;

I'd appreciate an explanation of why this is happening and how I can avoid it in the future

Community
  • 1
  • 1
Darryl Bayliss
  • 2,677
  • 2
  • 19
  • 28

2 Answers2

3

cin >> something leaves the trailing newline in the buffer, which would be ignored by the next cin >> something_else (presumably this is how you read the menu option). However, getline gets everything up to and including the next newline in the buffer, not ignoring whitespace. I.e. it gets nothing in this case (well, just the newline character).

Generally it's best not to mix use of both, it can get kinda messy.

Edit: To clarify, getline will remove that last newline from the buffer, but won't store it in your string.

BoBTFish
  • 19,167
  • 3
  • 49
  • 76
  • I used a switch case statement for menu selection just for your information. So you would suggest a strict use of ether getline or cin? – Darryl Bayliss Sep 27 '12 at 13:39
  • `switch`/`case` is fine for selecting a function to run based on the input, but not relevant to how you actually get that input. In general, just using one or the other of `>>` and `getline`, but not both, is the best bet. Dealing with both at the same time is a pain. – BoBTFish Sep 27 '12 at 13:42
1

It's because the newline character is still in the buffer so when it gets to the getline it sees it and skips over it. To avoid this you could place something like cin.ignore(25, "\n") on the line before. This will ignore 25 characters until it gets to the newline and then it takes that as well.

Gonzalo.-
  • 12,512
  • 5
  • 50
  • 82
Tony
  • 798
  • 7
  • 9