Use std::stringstream
. Its operator <<
is overloaded for all built-in types.
#include <sstream>
std::stringstream s;
s << "(" << c1 << "," << c2 << ")";
storedCorrect[count] = s.str();
This works like you'd expect - the same way you print to the screen with std::cout
. You're simply "printing" to a string instead. The internals of operator <<
take care of making sure there's enough space and doing any necessary conversions (e.g., double
to string
).
Also, if you have the Boost library available, you might consider looking into lexical_cast
. The syntax looks much like the normal C++-style casts:
#include <string>
#include <boost/lexical_cast.hpp>
using namespace boost;
storedCorrect[count] = "(" + lexical_cast<std::string>(c1) +
"," + lexical_cast<std::string>(c2) + ")";
Under the hood, boost::lexical_cast
is basically doing the same thing we did with std::stringstream
. A key advantage to using the Boost library is you can go the other way (e.g., string
to double
) just as easily. No more messing with atof()
or strtod()
and raw C-style strings.