具有结构指针数组的getline
getline with structure pointer array
我必须在课堂上学习内存管理,以及如何使用new
运算符动态分配内存。
我有一个结构是
struct Course
{
int courseNumber, creditHours;
string courseName;
char grade;
};
我正在尝试用for循环填充成员变量,但我不确定如何将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 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
:)
的返回值
相关文章:
- 重用字符数组和 cin.getline
- 如果用户输入的输入大于 char 数组,则 cin.getline 会跳过输入提醒
- 如何在 for 循环中解决潜在的 getline() 问题,数组的第一个索引没有显示?
- 填充字符数组的最佳方法(获取与cin.getline)
- 使用getline从文本文件中创建2个并行字符串数组
- 我在使用 cin.getline() 从用户那里获取 3 个字符串并使用指针数组来存储它们时遇到问题
- 如何使用getline从文件中读取到数组
- 使用getline,c 中的数组以相反的方式将所有字符单词转动
- 使用 Getline C++ 将每一行输入存储在数组中
- 使用 getline 从文件中获取多行并将它们输入到不同的数组中
- 为什么cin.getline分配给字符数组,但使用'='不会?
- 用getline在字符串中从文件中读取,然后将数字从int数组中的字符串划分
- 在 cpp 中使用 getline 输入数组中的空格分隔数字
- 动态数组大小和崩溃在 getline();
- 将"getline"与数组一起使用
- 如何使用 std::getline() 将文本文件读入 C++ 中的字符串数组
- Getline 直接到数组 C++,在一行中
- 当 cin.getline() 的第二个参数大于数组长度时,不可预测的字符串长度
- 当我超过第一个 getline() 的输入中的数组大小时,第二个 getline 或其他输入函数不起作用
- 具有结构指针数组的getline