I am doing a practice problem in HackerRank, and I am having trouble implementing the final task for this one issue I am having with classes.
It is a pretty simple program, it just uses a Student
class with setter and getter functions to take in a student's information (age, firstname, lastname, and academic standard), and uses an stringstream
to output that data.
However, at the very end is where I am having trouble. I am supposed to create a to_string()
function which returns a string
consisting of the above elements, separated by a comma (,
). I think I am just mis-understanding how to use ostringstream
.
#include <iostream>
#include <sstream>
#include <string>
class Student{
private:
int age;
std::string first_name;
std::string last_name;
int standard;
public:
void set_age(int age){
age = age;
}
int get_age(){
return age;
}
void set_standard(int standard){
standard = standard;
}
int get_standard(){
return standard;
}
void set_first_name(std::string first_name){
first_name = first_name;
}
std::string get_first_name(){
return first_name;
}
void set_last_name(std::string last_name){
last_name = last_name;
}
std::string get_last_name(){
return last_name;
}
std::string to_string(){
std::stringstream os;
os << age << "," << first_name << "," << last_name << "," << standard << std::endl;
return os.str();
}
};
int main() {
int age, standard;
std::string first_name, last_name;
std::cin >> age >> first_name >> last_name >> standard;
Student st;
st.set_age(age);
st.set_standard(standard);
st.set_first_name(first_name);
st.set_last_name(last_name);
std::cout << st.get_age() << "\n";
std::cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
std::cout << st.get_standard() << "\n";
std::cout << "\n";
std::cout << st.to_string();
return 0;
}
Input Example:
15
john
carmack
10
Expected output:
15
carmack, john
10
15,john,carmack,10
My output:
2
,
0
2,,,0