具有结构指针数组的getline

getline with structure pointer array

本文关键字:getline 数组 指针 结构      更新时间:2023-10-16

我必须在课堂上学习内存管理,以及如何使用new运算符动态分配内存。

我有一个结构是

struct Course
{
    int courseNumber, creditHours;
    string courseName;
    char grade;
};

我正在尝试用for循环填充成员变量,但我不确定如何将getlinecourseName一起使用。我可以使用常规的cin,但如果类名有空格,它就不起作用。

下面是我的代码和我尝试过的内容,但我得到了一个争论错误,courseArray是未定义的。

Course* readCourseArray(int &courses)                           //Read Courses
{
    cout<<"nHow many courses is the student taking?n";
    cin>>courses;
    const int *sizePTR = &courses;
    Course *coursePTR = new Course[*sizePTR]; 
    for(int count = 0; count < *sizePTR; count++)  //Enter course information
    {
        cout<<"nEnter student "<<count+1<<"'s course namen";
        getline(cin,courseArray[count].courseName);
        cout<<"nEnter student "<<count+1<<"'s course numbern";
        cin>>coursePTR[count].courseNumber;
        cout<<"nEnter student "<<count+1<<"'s credit hoursn";
        cin>>coursePTR[count].creditHours;
        cout<<"nEnter student "<<count+1<<"'s graden";
        cin>>coursePTR[count].grade;
    }

    return coursePTR;
}

指向数组的指针称为coursePTR,而不是courseArray。只需将名称courseArray替换为coursePTR即可。

对于这条线路:

const int *sizePTR = &courses;

你不必这么做,你可以直接使用courses(所以,从你使用sizePTR的地方删除所有*,然后将sizePTR更改为courses)。

此外,我希望您记住delete[] readCourseArray :) 的返回值