Advertisement

C++ and strings

Started by July 27, 2000 09:53 AM
3 comments, last by Armitage 24 years, 5 months ago
I ran into a small problem today, running NeHe''s bitmap tutorial c++ style. In the end, you''re supposed to display the value of float cnt1; on screen, by parsing it to a char-array. So the question is: How do I get the float attached to a std::string? An inverted atof, so to speak. I''d really like some help, since I don''t want to "clutter" my programs with variable arguments and/or sprintf...and yes, I know how to do that
A polar bear is a rectangular bear after a coordinate transform.
Commands like atoi() have counterparts such as itoa(). Have you tried the counterpart to atof() such as ftoa()?

It really depends on your compiler too, if it is pure ASNI standard it may not have some of these counterparts mentioned.

-AG
Advertisement
I was searching for ftoa, yes - in stdlib at least. If it's somewhere else, I don't know.
And I'm running msvc 6 - but my trusty stroustrup doesn't mention an ftoa either, which is why I posted.
But thanks for the effort.

The problem with (for instance) itoa is that it still requires me to allocate a char buffer - something I wish to avoid. I can read floats from the keyboard into a string, which is why I suspect there is a better way (with a stringstream or whatnot).

Edited by - Armitage on July 27, 2000 11:26:47 AM
A polar bear is a rectangular bear after a coordinate transform.
You could do something like this:

            #include <sstream>#include <string>  using namespace std;  void convert(string& str, float f){  ostringstream s;  s << f;  str = s.str();}         



I haven't compiled this here, but it should work, or be very close to it. Treat ostringstream just like an ostream.

---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!


Edited by - mossmoss on July 27, 2000 11:45:16 AM
Hmmm... you might even get away with this:

            #include <sstream>#include <string>  using namespace std;  void convert(string& str, float f){  ostringstream(str) << f;}            


But I'm sketchy as to whether that really works or not.


---- --- -- -
Blue programmer needs food badly. Blue programmer is about to die!


Edited by - mossmoss on July 27, 2000 11:43:07 AM

This topic is closed to new replies.

Advertisement