-2

So I am relatively new to C++ and I was doing a small project where I have the user enter a movie title, rating, and year. For the first run through, the program works well. After the user enters the desired information I print it back to the screen with no problem. However, when I create a second movie object to do the same thing during the same run it skips the section where it asks for the Title and goes directly to the rating. Any ideas? It's most likely a noob error. My Code is below.

MovieProject.cpp

#include "stdafx.h"
#include "Movie.h"
#include <iostream>
#include <string>
using namespace std;

int main()
{
    Movie starwars;
    starwars.MovieTeller(starwars);
    Movie FerrisBueller;
    FerrisBueller.MovieTeller(FerrisBueller);
    Movie TheFoxandTheHound;
    TheFoxandTheHound.MovieTeller(TheFoxandTheHound);
    return 0;
}

Movie.cpp

    #include "stdafx.h"
    #include "Movie.h"
    #include <string>
    #include <iostream>

using namespace std;

Movie::Movie()
{
    cout << "What is the title of your movie:";
    getline(cin,Title);
    cout << "What is the Rating:";
    getline(cin,Rating);
    cout << "What year was it made:";
    cin >> Year;
    cout << "\n" << endl;
    if (Year > 2016) {
        cout << "Comon Dude stop messing around" << endl;
        exit(404);
    }
}

void Movie::MovieTeller(Movie a) {
    cout << "Title:" << Title << "\n" << "Rating:" << Rating << "\n" << "Year:" << Year << "\n" << endl;
}
Movie::~Movie()
{
}

Movie.h

#pragma once
#include <iostream>
using namespace std;
class Movie
{
public:
    Movie();
    ~Movie();
    void MovieTeller(Movie a);
private:
    string Title;
    string Rating;
    int Year;
};
Malcolm
  • 43
  • 8

2 Answers2

1

This happens all the time when you use getline following a read of a number with >> operator.

Here is what's happening: the cal cin >> Year reads all digits from user's input, but leaves the trailing \n in place, because it is not part of the number. When getline is called in a constructor of the next object, the \n is still there, so getline counts this input as an empty line.

You can fix this by adding getline after reading the year, and ignoring its result. However, a better approach would be removing input from the constructor altogether, and moving it into a custom input operator for your class. This way your code would be a lot cleaner.

Sergey Kalinichenko
  • 675,664
  • 71
  • 998
  • 1,399
0

There is also another problem with the code: the method MovieTeller is not acting on instance a passed as an argument to this method. It should be

void Movie::MovieTeller(Movie a) {
    cout << "Title:" << a.Title << "\n" << "Rating:" << a.Rating << "\n" << "Year:" << a.Year << "\n" << endl;
}

OR This method should be declared as public method without any input arguments.

Aurora0001
  • 10,827
  • 5
  • 47
  • 50