Reputation: 4305
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;
}
};
Upvotes: 0
Views: 1172
Reputation:
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.
Upvotes: 7
Reputation: 22641
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.)
Upvotes: 2
Reputation: 99695
You could use boost::lexical_cast
as follows:
return getName()+"\t"+boost::lexical_cast<std::string>(Damage)+
"\t"+boost::lexical_cast<std::string>(Cost);
Upvotes: 2