Storing floats to a string?
Is it possible to do this?
I have tried something like this but it has not worked:
Code:
float x = 9;
float y = 33;
string sum = x;
sum += "+";
sum += y;
I would want the outcome to look like "9+33"
I know that seems dumb but I am actually trying something on a larger scale.
I know I could use:
Code:
cout << x << "+" << y
but I need to display this a lot so I would like it to be a string.
Thanks.
Re: Storing floats to a string?
This topic has no doubt been covered already on these forums as well as google, but here is the answer anyway:
Code:
#include <string>
#include <sstream>
#include <exception>
std::string to_string(int x)
{
std::ostringstream o;
if (!(o << x))
throw std::exception("Couldn't parse integer in to_string.");
return o.str();
}
int main()
{
std::string x = "12 * 12 = " + to_string(12 * 12);
std::cout << x << std::endl;
return 0;
}
There is also boost::lexical_cast, but if you are new to C++ it's easier to forget 3rd party libraries until you get more familiar with the language.
Re: Storing floats to a string?
Re: Storing floats to a string?
Thanks. I actually did search Google but for some reason found nothing.