|
-
May 15th, 2008, 09:36 PM
#1
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.
-
May 15th, 2008, 09:47 PM
#2
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.
Last edited by Mybowlcut; May 15th, 2008 at 09:51 PM.
-
May 16th, 2008, 12:33 AM
#3
Re: Storing floats to a string?
Before post, make an effort yourself, try googling or search here.
When posting, give a proper description of your problem, include code* and error messages.
*All code should include code tags
-
May 16th, 2008, 02:02 PM
#4
Re: Storing floats to a string?
Thanks. I actually did search Google but for some reason found nothing.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|