Help with cin/getline

I'm working on an exercise in "Thinking in C++" dealing with Stack structures. The following main code almost is working perfectly, except that right after I enter the number of movies I'd like to input, the program is skipping over the first title. It looks like "Enter the title: Enter the year: ..." I can input the title fine on each entry after the first. I tried doing "getline(cin, nMovies);" on line 15, but the compiler didn't like that. What am I missing?

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
#include "MyStruct.h"
#include "Movies.h"
#include <iostream>
#include <string>
#include <vector>
using namespace std;

//PROTOTYPES
void getMovies ( vector<Movies>& movieVec, int numMovies );


int main() {
	int nMovies;
	cout << "How many movies would you like to enter: ";
	cin >> nMovies; 
	cout << "\n";
	vector<Movies> movieVec;
	getMovies( movieVec, nMovies);
	
	//...Other code dealing with the stack

} ///:~*/


void getMovies ( vector<Movies>& movieVec, int numMovies ) {
	string title;
	string year;
	string actors;
	Movies currentMovie;
	for ( int i = 0; i < numMovies; i++ ) {
		cout << "Enter the movie's title: ";
		getline ( cin, title );
		currentMovie.setTitle( title );
		cout << "Enter the movie's year: ";
		getline ( cin, year );
		currentMovie.setYear( year );
		cout << "Enter the movie's actors: ";
		getline ( cin, actors );
		currentMovie.setActors( actors );
		movieVec.push_back(currentMovie);
	}
}
Last edited on
You have a leftover '\n' in the buffer after line 15. This becomes the delimiter for the first iteration of line 32. As a result, the first movie title is always blank.

Put cin.ignore(80, '\n'); after extracting the amount of movies. 80 would be characters to ignore until it finds the new line character.

Otherwise, you would really break your program if you did something like this:
How many movies would you like to enter:
answer: 15 a a a a a a a
Ignore... that's a handy one. Thanks for the help LO.
Topic archived. No new replies allowed.