getline function

I am using the getline function to read until the end of the line when the user enters a movie title. I am having problems because it reads the movie title until the end of the line but for some reason skips the first word. For example, when I run the program to test it and enter "Fifty Shades of Grey" for the movie title and I output the movie name just to test it, all it displays is "Shades of Grey." The Fifty disappears. Any help would be awesome! Thanks.

1
2
3
4
5
6
7
8
9
10
11
12
13
 string specifyMovieName()
{
    string movieName;
    cout << "Please enter a movie name " << endl;
    cin >> movieName;
    getline(cin, movieName);
    cout << endl;
    return movieName;	 
}

void addMovie(string movieName, movieType movieLibrary[size], const int size)
{
	cout << "Please Add the Following Information About the Movie " << movieName << endl;
Last edited on
usually, placing a cin.ignore() above the getline would fix it.

1
2
cin.ignore(); // To skip the \n character.
getline(cin, movieName);
Hi. From my experiences, when working with std::cin and std::getline, you usually want to insert a std::cin.ignore(); after each std::cin

This prevents std::getline from being skipped. You may be able to find some better explanations. I've never really understood why it's like that. Only that I've implemented it many times for my programming courses, and nothing has gone wrong.
1
2
    cin >> movieName;
    getline(cin, movieName);


So the first statement takes the string up to the first whitespace (-> "Fifty") and puts it in movieName.

Then the next statement reads in the rest of the line up to the newline character (-> "Shades of Grey") and overwrites the contents of movieName with it.


Just have a single input statement
getline(cin, movieName);
and there you are.
Last edited on
Topic archived. No new replies allowed.