user1770094
user1770094

Reputation: 87

Appending and returning a string

I've got a class and one of its functions is to type out some information with the help of previous functions.

string printResult()
{
    string result;

    cout<<"\n"<<getName()<<" bla bla bla "<<getPoints()<<" blabla.";

    return result;
}

Where getName and getPoints are obviously those other functions.

My question is: How should I redo/change this part

cout<<"\n"<<getName()<<" bla bla bla "<<getPoints()<<" blabla.";

to become a string of its own which I can return,with this exact content?

Upvotes: 1

Views: 436

Answers (3)

Bartek
Bartek

Reputation: 11

Use stringstream.

Some examples here: http://www.dreamincode.net/forums/topic/95826-stringstream-tutorial/

Upvotes: 0

imreal
imreal

Reputation: 10348

You can just use the append() member of std::string:

result.append(getName());
result.append(getPoints());

Assuming those functions return a string or a char*.

Upvotes: 0

john
john

Reputation: 87959

Use a stringstream

#include <sstream>

string printResult()
{
    ostringstream result;

    result<<"\n"<<getName()<<" bla bla bla "<<getPoints()<<" blabla.";

    return result.str();
}

Upvotes: 5

Related Questions