In modern C++ you could say:
std::string ClassName::toString() const
{
return "Position: (" + std::to_string(position.x) + ", "
+ std::to_string(position.y) + ", "
+ std::to_string(position.z) + ")\n";
}
If you must use printf
, you can still use a string, but you have to resize it first.
std::string ClassName::toString() const
{
static const int initial_size = 1024;
std::string s(initial_size);
int ret = std::snprintf(&s[0], s.size(), "Position: (%f, %f, %f)\n", position.x, position.y, position.y);
s.resize(ret);
// handle overflow: print again
if (s.size() > initial_size)
{
std::snprintf(&s[0], s.size(), "Position: (%f, %f, %f)\n", position.x, position.y, position.y);
}
return s;
}
Note that &s[0]
gives you a pointer to mutable char, and indeed to the first element of a whole array of those of size s.size()
.