-
Converting a float to char*
I'm making a game in OpenGL which already has a function to print a string and now I'm trying to add a function to print a numeric value in the same way by converting the number to a character string and then sending it to the same printing function(which works). I've tried gcvt, sprintf etc. and some(including the mentioned 2) have printed the correct value initially, but they make my program freeze. so if anyone knows a good way to do this, that'd be great. The code I'm currently trying to use is:
void print_numberf(float tX, float tY, float tSize, float fNumber)
{
char num[10];
//the problem
_gcvt(fNumber, 10, num);
//the following line of code is fine
print_string(tX, tY, 0, tSize, 1.0, num, FALSE);
return;
}
Thanks in advance.
-MAD Programming's
Daniel Borgman
-
i typed this
char num[10];
_gcvt((double)1000/3, 10, num);
cout<<num;
and it gave 333.3333333 -->10 + 1 characters.
i guess this overflow your num[].
http://www.cplusplus.com/ref/cstdlib/gcvt.html
link say use a buffer which is 8-9 character larger than ...
Last edited by mr1yh1; 12-17-2005 at 01:41 AM.
-
yes, thats likely the problem. A float has 15 or so digits, make num[20] to be safe.
-
_gcvt is not a standard function so I can't vouch for it. However, a decent conversion function should be able to truncate the result so that it fits into the buffer. I would use strinsgstream for such conversions anyway -- it's safer and simpler.
Danny Kalev
-
Yes!
Thanks a bunch for the help, you guys. I increased the size of num and it worked, which is awesome. Thanks again.
-
Aw, jeez. I just tried to impliment it with a variable passed for the number and it didn't work, so I was wondering how strinsgstream works. Just in case, here's my current code again:
void print_numberf(float tX, float tY, float tSize, float fNumber)
{
char num[20];
_gcvt(fNumber, 10, num);
print_string(tX, tY, 0, tSize, 1.0, num, FALSE);
return;
}
and I also used
sprintf(num, "%d", fNumber);
which didn't work.
-
You can find examples of stringstream usage here: http://www.devx.com/DevX/LegacyLink/9399
Danny Kalev
-
I actually can't use sstream with Dev-C++(my compiler)
Similar Threads
-
By Tim Overbay in forum .NET
Replies: 4
Last Post: 02-27-2002, 03:01 PM
-
By Curtis Nelson in forum Java
Replies: 1
Last Post: 03-29-2001, 11:12 AM
-
By Marie in forum Database
Replies: 0
Last Post: 11-20-2000, 05:37 AM
-
By Marie in forum VB Classic
Replies: 0
Last Post: 11-20-2000, 05:32 AM
-
Replies: 1
Last Post: 10-11-2000, 12:23 PM
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
|
Top DevX Stories
Easy Web Services with SQL Server 2005 HTTP Endpoints
JavaOne 2005: Java Platform Roadmap Focuses on Ease of Development, Sun Focuses on the "Free" in F.O.S.S.
Wed Yourself to UML with the Power of Associations
Microsoft to Add AJAX Capabilities to ASP.NET
IBM's Cloudscape Versus MySQL
|
Bookmarks