Use streams, in your case, a stringstream:
#include <sstream>
...
std::stringstream ss;
ss << n << '/' << d;
Later, when done with your work, you can store it as an ordinary string:
const std::string s = ss.str();
Important (side-) note: Never do
const char *s = ss.str().c_str();
stringstream::str()
produces a temporary std::string
, and according to the standard, temporaries live until the end of the expression. Then, std::string::c_str()
gives you a pointer to a null-terminated string, but according to The Holy Law, that C-style-string becomes invalid once the std::string
(from which you receved it) changes.
It might work this time, and next time, and even on QA, but explodes right in the face of your most valuable customer.
The std::string
must survive until the battle is over:
const std::string s = ss.str(); // must exist as long as sz is being used
const char *sz = s.c_str();