I have this problem for c++ coding. You have been given a Student class. A user
ID: 3680553 • Letter: I
Question
I have this problem for c++ coding.
You have been given a Student class. A user will insert multiple names followed by the word "STOP" With each name, create a Student pointer and insert it into the "students" vector. You must print all the names in the vector in reverse order.
#pragma once
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student
{
private:
string name;
public:
Student(string name);
string getName();
void setName(string newName);
~Student();
};
Student::Student(string studentName)
{
name = studentName;
}
string Student::getName()
{
return name;
}
void Student::setName(string newName)
{
name = newName;
}
Student::~Student()
{
}
//
// You may insert a function here
int main()
{
vector<Student*> students;
return 0;
}
Explanation / Answer
I have added the function required and did changed the main method accordingly, happy execution.
#pragma once
#include <iostream>
#include <string>
#include <vector>
using namespace std;
class Student
{
private:
string name;
public:
Student(string name);
string getName();
void setName(string newName);
~Student();
};
Student::Student(string studentName)
{
name = studentName;
}
string Student::getName()
{
return name;
}
void Student::setName(string newName)
{
name = newName;
}
Student::~Student()
{
}
//
// You may insert a function here
Student* input(){
string s;
cout << "Enter a student name (or stop)" << endl;
retry:
getline(cin, s);
if(s.size()==0){
cout << "Enter a NAME or STOP" << endl;
goto retry;
}
return s=="stop" || s=="STOP"? 0 : new Student(s);
}
int main() {
vector<Student*> students;
for(;;){
Student* pStudent = input();
if(!pStudent){
break;
}
students.push_back(pStudent);
}
for (auto i = students.rbegin(); i !=students.rend(); ++i ) {
cout << (*i)->getName() << endl;
}
for(auto p:students){
delete p;
}
return 0;
}