What is the easiest way to convert from int
to equivalent string
in C++. I am aware of two methods. Is there any easier way?
(1)
It's rather easy to add some syntactical sugar that allows one to compose strings on the fly in a stream-like way
#include
#include
struct strmake {
std::stringstream s;
template strmake& operator << (const T& x) {
s << x; return *this;
}
operator std::string() {return s.str();}
};
Now you may append whatever you want (provided that an operator << (std::ostream& ..)
is defined for it) to strmake()
and use it in place of an std::string
.
Example:
#include
int main() {
std::string x =
strmake() << "Current time is " << 5+5 << ":" << 5*5 << " GST";
std::cout << x << std::endl;
}