我必须学习类中的内存管理以及如何动态分配内存与new
运算符。getline与结构指针数组
我有一个结构是
struct Course
{
int courseNumber, creditHours;
string courseName;
char grade;
};
我试图用填充成员变量的循环,但我不能确定如何使用getline
与courseName
。我能够使用常规的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;
}
返回值? – Nawaz 2012-02-24 03:33:09
啊我仍然有点困惑与传递指针和东西,我认为我有问题设置一个int int的const int值,但我不记得。它虽然工作。 – sircrisp 2012-02-24 03:45:59
如果你发现你的输入不同步,你可能会发现你需要'std :: cin.ignore(std :: numeric_limits :: max(),'\ n');'as循环中的最后一行。 –
2012-02-24 04:35:09