sircrisp
sircrisp

Reputation: 1067

How do I pass a string to a pointer to object class array?

OK so I have made a class called Courses with private member functions courseName, creditHours,grade, and courseNumber.

Since this is homework and we just went over pointers and dynamic memory allocation, I have to read in how many courses the student has taken, dynamically create an array of Course type, and prompt the user to enter information regarding the courses. This is how the instructor wants it done.

Below is the function I have for creating and filling the array but I am unsure of how to actually fill it.

Course readCourseArray(int coursesTaken)
{
    cout<<"\nHow many courses has the student taken?\n";
    cin>>coursesTaken;

    Course *courses = new Course[coursesTaken];

    for(int count = 0; count < coursesTaken; count++)
        {
            cout<<"Enter name for course "<<count+1<<endl;
            getline(cin,courses[count].courseName);
            }

    return *courseArray;

}

My problem is the getline portion. I get a red squiggle and it says courseName is inaccessible and I cant think of another way to run through the loop.

In my class specification file I have

void setCourseName (string _courseName)
{courseName=_courseName;};

But I don't know how I would use that to cycle through the array either.

Upvotes: 1

Views: 118

Answers (2)

personak
personak

Reputation: 539

It looks like courseName is a private member variable. private means you can't access it outside of the class. To use getline, create a temporary string:

string temp;
getline(cin, temp);
courses[count].setCourseName(temp);

Upvotes: 1

Marlon
Marlon

Reputation: 20314

courseName is a private variable, so you can't access it like that. Here is what you should do:

  1. Make a temporary std::string variable.
  2. Use getline on that string.
  3. Pass that string to setCourseName.

Upvotes: 1

Related Questions