[英]getline with structure pointer array
I have to learn memory management in class and how to dynamically allocate memory with the new
operator. 我必须学习类中的内存管理以及如何使用
new
运算符动态分配内存。
I have a struct that is 我有一个结构是
struct Course
{
int courseNumber, creditHours;
string courseName;
char grade;
};
I am trying to fill the member variables with a for loop but I am unsure how to use a getline
with courseName
. 我想用填充成员变量的循环,但我不能确定如何使用
getline
与courseName
。 I was able to use a regular cin
but it won't work if the class name has spaces. 我能够使用普通的
cin
但如果类名有空格则无法使用。
Below is my code and what I've tried but I get a arguement error that courseArray is undefined. 下面是我的代码和我尝试过的内容,但收到一个争论,提示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;
}
The pointer to your array is called coursePTR
, not courseArray
. 指向数组的指针称为
coursePTR
,而不是courseArray
。 Just replace the name courseArray
with coursePTR
. 只需用
coursePTR
替换名称courseArray
coursePTR
。
For this line: 对于这一行:
const int *sizePTR = &courses;
You don't have to do that, you can just use courses
directly (so, remove all the *
from the places you use sizePTR
then change sizePTR
to courses
). 你不必这样做,你就可以使用
courses
直接(所以,删除所有*
从使用场所sizePTR
然后更改sizePTR
到courses
)。
Also I hope you are remembering to delete[]
the return value of readCourseArray
:)
另外,我希望您还记得
delete[]
readCourseArray
的返回值:)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.