In case you're interested, here's how you could do it using stringstreams:
Code:
#include <string>
#include <sstream>
std::string ltos(long number) {
std::ostringstream stream;
stream << number;
return stream.str();
}
My favourite method, though, is to use something like this.
Code:
#ifndef CALLIS_MISC_STREAM_AS_STRING_H
#define CALLIS_MISC_STREAM_AS_STRING_H
#include <sstream>
#include <string>
namespace Callis {
namespace Misc {
/** A simple class which in effect that adds an insertion operator, <<, to the
std::string class, as users of streams such as cout or stringstream expect.
This class can be used as a temporary object in places where an ordinary
string would be expected; for example:
void print(std::string str);
print(StreamAsString() << "Answer = " << 42);
This implementation is quite efficient, only converting its internal
stringstream to a string when operator std::string() is called.
*/
class StreamAsString {
private:
/** The internal stringstream used to implement the insertion operator <<.
*/
std::ostringstream stream;
protected:
std::ostringstream &get_stream() { return stream; }
const std::ostringstream &get_stream() const { return stream; }
public:
/** Adds an object to the end of the internal stringstream.
*/
template <typename T>
StreamAsString &operator << (const T &data);
/** Converts the internal stringstream to an std::string automatically.
*/
operator std::string() const;
};
template <typename T>
StreamAsString &StreamAsString::operator << (const T &data) {
get_stream() << data;
return *this;
}
inline StreamAsString::operator std::string() const {
return get_stream().str();
}
} // namespace Misc
} // namespace Callis
#endif
Then as the comment indicates you can use code like
Code:
long long_answer = 42;
std::string answer = StreamAsString() << long_answer;
and the StreamAsString object will automatically be converted to a std::string.