0

Damage and Cost are integers, but as you can see in the code below I want to concatenate them with a string (if that's the right word). How can I do this?

class Weapon : Shopable{ private: int Damage; public: std::string getDesc() const{ return getName()+"\t"+Damage+"\t"+Cost; } }; 

3 Answers 3

7

Provide yourself with this template:

#include <sstream> template <class TYPE> std::string Str( const TYPE & t ) { std::ostringstream os; os << t; return os.str(); } 

You can then say:

return getName() + "\t" + Str( Damage ) + "\t" + Str(Cost); 

Note this is pretty much equivalent to Boost's lexical_cast, and to similar facilities in the upcoming standard. Also note that this function trades performance for convenience and type-safety.

Sign up to request clarification or add additional context in comments.

1 Comment

Is that the only way? I assumed there was some easy built in method I hadn't come across in my searches. In Lua (my primary language) there's just a tostring() function.
2

You could use boost::lexical_cast as follows:

return getName()+"\t"+boost::lexical_cast<std::string>(Damage)+ "\t"+boost::lexical_cast<std::string>(Cost); 

Comments

2

You've already accepted @unapersson's answer, but for the record I would do this...

std::string getDesc() const { std::ostringstream ss; ss << getName() << "\t" << Damage << "\t" << Cost; return ss.str(); } 

It only constructs one stream object instead of creating and throwing them away for each conversion, and it looks a bit nicer too.

(This is the C++ way - there's no general 'toString' member like other languages, generally we use string streams or a one-off function like in @unapersson's answer.)

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.