0

I have skipped the above part It is a normal c++ program using classes which prints name,age and standard

Code is as follows:

string to_string()
{
    return age,last_name,first_name,standard; //PROBLEM IS HERE
}
};

int main() {
    int age, standard;
    string first_name, last_name;

    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);


    cout << st.get_age() << "\n";
    cout << st.get_last_name() << ", " << st.get_first_name() << "\n";
    cout << st.get_standard() << "\n";
    cout << "\n";
    cout << st.to_string();

    return 0;
}
SingerOfTheFall
  • 29,228
  • 8
  • 68
  • 105
A.Bora
  • 27
  • 2
  • 10

1 Answers1

3
string to_string()
{
    return age,last_name,first_name,standard; //PROBLEM IS HERE
}

I assume you want to concatenate all the member data into one string and return that, but the comma operator just evaluates its first expression, throws away the value, then returns the value of the second expression.

You could make a std::string then repeatedly append to it. I think std::stringstream is a bit cleaner for things like this though:

string to_string()
{
    std::stringstream ss;
    ss << age << ' ' << last_name << ' ' << first_name << ' ' << standard;
    return ss.str();
}
TartanLlama
  • 63,752
  • 13
  • 157
  • 193
  • Then an error comes in these statements: Student st; st.set_age(age); st.set_standard(standard); st.set_first_name(first_name); st.set_last_name(last_name); undefined reference to Student::set_blah – A.Bora Sep 25 '15 at 08:24
  • @A.Bora did you define those functions? Did you link with the object file produced? Those errors are in code you have not shown here. – TartanLlama Sep 25 '15 at 08:26
  • but arent those inbuilt functions of #include ? – A.Bora Sep 25 '15 at 08:32
  • @A.Bora The issue is that the linker can't find definitions of your `Student::set_x` functions. That's unrelated to `std::stringstream`. – TartanLlama Sep 25 '15 at 08:33
  • I have defined the functions void set_age(int age); – A.Bora Sep 25 '15 at 08:38
  • That's a declaration, not a definition. They need to be defined and the object file containing their definition must be linked into the executable. – TartanLlama Sep 25 '15 at 08:42
  • can you explain it briefly? – A.Bora Sep 25 '15 at 09:07
  • @A.Bora please read [this](http://stackoverflow.com/questions/12573816/what-is-an-undefined-reference-unresolved-external-symbol-error-and-how-do-i-fix). – TartanLlama Sep 25 '15 at 09:12