Convert a string to float and vice versa

F

Flyingaway

I am just wondering what is the most elegant and efficient way to do
such type conversion.

Thanks,

Flyingway
 
I

Ivan Vecerina

Flyingaway said:
I am just wondering what is the most elegant and efficient way to do
such type conversion.
Consider using boost::lexical_cast
See: http://www.boost.org/libs/conversion/lexical_cast.htm

For maximum efficiency, one could use a statically allocated
buffer and the functions atof (in <cstdlib>) and ftoa(when
available, otherwise sprintf). But for the latter you need
to be very careful with buffer overflows - using snprintf
may help...
 
F

Flyingaway

Hi Ivan,

That is so helpful! You are greatly appreciated. Thanks.

Best wishes,

Flying...
 
S

Stu

Ivan said:
Consider using boost::lexical_cast
See: http://www.boost.org/libs/conversion/lexical_cast.htm

For maximum efficiency, one could use a statically allocated
buffer and the functions atof (in <cstdlib>) and ftoa(when
available, otherwise sprintf). But for the latter you need
to be very careful with buffer overflows - using snprintf
may help...

Why not just use a stringstream? Something like:

#include <sstream>

....

std::stringstream ss;

....

// Cast to float...
ss << some_string;
ss >> some_float;

....

// Cast to string...
ss >> some_float;
ss << some_string;

....


No third party library or C functions needed...


Stu
 
S

Stu

Stu said:
// Cast to string...
ss >> some_float;
ss << some_string;

Whoops, copy and paste error! It should look like this:

// Cast to string...
ss << some_float;
ss >> some_string;


Stu
 
I

Ivan Vecerina

Seemed to be the most elegant.
That was for the most efficient.
Why not just use a stringstream? Something like:

I totally agree it's a good solution (and it is actually
boost::lexical_cast uses by default). I had narrowly
answered the question that was posted...

Cheers,
Ivan
 
J

Jack Klein

Consider using boost::lexical_cast
See: http://www.boost.org/libs/conversion/lexical_cast.htm

For maximum efficiency, one could use a statically allocated
buffer and the functions atof (in <cstdlib>) and ftoa(when
available, otherwise sprintf). But for the latter you need
to be very careful with buffer overflows - using snprintf
may help...

Poor advice, atof and its siblings produce undefined behavior if the
converted value is outside the range of the type.

That is specifically why the strtod and siblings were invented.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top