Click to See Complete Forum and Search --> : Storing floats to a string?


Geralds Mod
May 15th, 2008, 09:36 PM
Is it possible to do this?
I have tried something like this but it has not worked:

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:

cout << x << "+" << y

but I need to display this a lot so I would like it to be a string.

Thanks.

Mybowlcut
May 15th, 2008, 09:47 PM
This topic has no doubt been covered already on these forums as well as google (http://www.google.com.au/search?hl=en&q=int+to+string+C%2B%2B&btnG=Google+Search&meta=), but here is the answer anyway:
#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 (http://www.boost.org/doc/libs/1_35_0/libs/conversion/lexical_cast.htm), but if you are new to C++ it's easier to forget 3rd party libraries until you get more familiar with the language.

laasunde
May 16th, 2008, 12:33 AM
Faq: How to convert a numeric type to a string? (http://www.codeguru.com/forum/showthread.php?t=231056)

Geralds Mod
May 16th, 2008, 02:02 PM
Thanks. I actually did search Google but for some reason found nothing.