2012-02-24 88 views
1

我必须学习类中的内存管理以及如何动态分配内存与new运算符。getline与结构指针数组

我有一个结构是

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

我试图用填充成员变量的循环,但我不能确定如何使用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 name\n"; 
     getline(cin,courseArray[count].courseName); 
     cout<<"\nEnter student "<<count+1<<"'s course number\n"; 
     cin>>coursePTR[count].courseNumber; 
     cout<<"\nEnter student "<<count+1<<"'s credit hours\n"; 
     cin>>coursePTR[count].creditHours; 
     cout<<"\nEnter student "<<count+1<<"'s grade\n"; 
     cin>>coursePTR[count].grade; 
    } 


    return coursePTR; 
} 
+1

返回值? – Nawaz 2012-02-24 03:33:09

+0

啊我仍然有点困惑与传递指针和东西,我认为我有问题设置一个int int的const int值,但我不记得。它虽然工作。 – sircrisp 2012-02-24 03:45:59

+0

如果你发现你的输入不同步,你可能会发现你需要'std :: cin.ignore(std :: numeric_limits :: max(),'\ n');'as循环中的最后一行。 – 2012-02-24 04:35:09

回答

3

指针到您的数组被称为coursePTR,不courseArray。请用coursePTR替换名称courseArray

对于此行:

const int *sizePTR = &courses; 

你没有做到这一点,你可以直接使用courses(所以,请从您使用sizePTR然后更改sizePTRcourses地方所有*)。

我也希望你记住要delete[]为什么你使用`sizePTR`的readCourseArray:)

+0

Derp这是谢谢我使用不同函数的名称。 – sircrisp 2012-02-24 03:41:17