gpt4 book ai didi

c++ - 将字符串元素添加到动态数组

转载 作者:行者123 更新时间:2023-11-28 05:13:24 25 4
gpt4 key购买 nike

解析文件并需要使用数组将学生添加到结构 vector 中,该数组包含特定于该类(class)行的学生姓名。

在我的 course.h 文件中:

struct Course {
std::string name;
int enrollment;
int maxEnrollment;

std::string* students; ///< array of student names

Course(std::string courseName, int maxEnrollmentPermitted);

bool enroll(std::string studentName);

void print(std::ostream& output);
};

在我的 course.cpp 文件中:

bool Course::enroll(std::string studentName) {
this->students = new std::string[studentName];
if (this->enrollment < this->maxEnrollment) {
this->enrollment++;
return true;
}
else {
return false;

在我的源文件中:

void processEnrollmentRequests(istream& enrollmentRequestsFile, vector<Course>& courses) {
// Read the requests, one at a time, serving each one
string courseName;
enrollmentRequestsFile >> courseName;

while (enrollmentRequestsFile) {
enrollmentRequestsFile >> ws;
string studentName;
getline(enrollmentRequestsFile, studentName);

int pos = search(courses, courseName);
if (pos >= 0) {
// Found a matching course
bool enrolled = courses[pos].enroll(studentName);
if (enrolled) {
cout << studentName << " has enrolled in " << courseName << endl;
}
else {
// course is full
cout << studentName << " cannot enroll in " << courseName << endl;
}
}
else {
// course does not exist
cout << studentName << " cannot enroll in " << courseName << endl;
}
enrollmentRequestsFile >> courseName;
}
}
}
}

我似乎无法使用 this->students = new std::string[studentName] 将收集到的学生姓名添加到数组中。收到一条错误消息,提示 must have integral or enumeration type

最佳答案

new SomeThing[size] 用于声明数组。使用字符串作为大小没有意义。

假设 students 的大小限制为 maxEnrollment,您可以使用:

if (this->enrollment < this->maxEnrollment) {
this->students[this->enrollment++] = studentName;
return true;
}
else {
return false;

关于c++ - 将字符串元素添加到动态数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43128686/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com