[英]getline with structure pointer array
我必須學習類中的內存管理以及如何使用new
運算符動態分配內存。
我有一個結構是
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;
}
指向數組的指針稱為coursePTR
,而不是courseArray
。 只需用coursePTR
替換名稱courseArray
coursePTR
。
對於這一行:
const int *sizePTR = &courses;
你不必這樣做,你就可以使用courses
直接(所以,刪除所有*
從使用場所sizePTR
然后更改sizePTR
到courses
)。
另外,我希望您還記得delete[]
readCourseArray
的返回值:)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.