karite36
karite36

Reputation: 47

Second Instance Of Object Not Working Correctly

So I'm working on an example from my class textbook Starting Out With C++: Early Objects, and I'm running into an issue. I'm instructed to create a program that reads in some data and prints it at the end, 2 instances in total. When the second instance (md2) runs, it it doesn't let me enter anything in the first field. This is really bugging me, and I can't figure it out. Thanks in advance!

#include <iostream>

using namespace std;

class MovieData
{
private:
    string movieTitle;
    string movieDirector;
    int movieYear;
    int movieRunTime;
public:
    MovieData()
    {
        GetTitle();
        GetDirector();
        GetYear();
        GetRunTime();
    }

    void GetTitle()
    {
        cout << "Specify A Title\n";
        getline(cin, movieTitle);
        cout << endl;
    }
    void GetDirector()
    {
        cout << "Specify A Director" << endl;
        getline(cin, movieDirector);
        cout << endl;
    }
    void GetYear()
    {
        cout << "Specify A Year" << endl;
        cin >> movieYear;
        cout << endl;
    }
    void GetRunTime()
    {
        cout << "Specify A Duration In Minutes" << endl;
        cin >> movieRunTime;
        cout << endl;
    }

    void SetTitle()
    {
        cout << "R" << movieTitle << endl;
    }
    void SetDirector()
    {
        cout << "R" << movieDirector << endl;
    }
    void SetYear()
    {
        cout << "R" << movieYear << endl;
    }
    void SetRunTime()
    {
        cout << "R" << movieRunTime << endl;
    }


};

void PrintData(MovieData md);

int main() {
    MovieData md1;
    PrintData(md1);
    MovieData md2;
    PrintData(md2);
}


void PrintData(MovieData md)
{
    md.SetTitle();
    md.SetDirector();
    md.SetYear();
    md.SetRunTime();
    cout << endl;
}

Upvotes: 2

Views: 121

Answers (1)

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726609

The reason why this happens is that the last item that you read from end-user when preparing md1 is an int. End-user types that integer in, and then presses Enter. C++ reads the integer into movieRunTime, but leaves the character code for Enter buffered for the next read.

The next time around, that enter character code gets returned to GetTitle, meaning that the title becomes an empty string. That is the behavior that you are observing.

To fix this problem, add a call to std::cin.ignore to your constructor:

MovieData()
{
    GetTitle();
    GetDirector();
    GetYear();
    GetRunTime();
    std::cin.ignore(256, '\n');
}

Upvotes: 5

Related Questions