Is there a function similar to atoi which converts a string to float instead of to integer?
like atoi but to float
32.3k Views Asked by lital maatuk AtThere are 11 best solutions below

strtof
From the man page
The strtod(), strtof(), and strtold() functions convert the initial portion of the string pointed to by nptr to double, float, and long double representation, respectively.
The expected form of the (initial portion of the) string is optional leading white space as recognized by isspace(3), an optional plus (‘‘+’’) or minus sign (‘‘-’’) and then either (i) a decimal number, or (ii) a hexadecimal number, or (iii) an infinity, or (iv) a NAN (not-a-number).
/man page>
atof converts a string to a double (not a float as it's name would suggest.)

boost::lexical_cast<float>(str);
This template function is included in the popular Boost collection of libraries, which you'll want learn about if you're serious about C++.

Convert a string to any type (that's default-constructible and streamable):
template< typename T >
T convert_from_string(const std::string& str)
{
std::istringstream iss(str);
T result;
if( !(iss >> result) ) throw "Dude, you need error handling!";
return result;
}

As an alternative to the the already-mentioned std::strtof()
and boost::lexical_cast<float>()
, the new C++ standard introduced
float stof(const string& str, size_t *idx = 0);
double stod(const string& str, size_t *idx = 0);
long double stold(const string& str, size_t *idx = 0);
for error-checking string to floating-point conversions. Both GCC and MSVC support them (remember to #include <string>
)

This would also work ( but C kind of code ):
#include <iostream>
using namespace std;
int main()
{
float myFloatNumber = 0;
string inputString = "23.2445";
sscanf(inputString.c_str(), "%f", &myFloatNumber);
cout<< myFloatNumber * 100;
}
See it here: http://codepad.org/qlHe5b2k

As an alternative to all above, you may use string stream. http://cplusplus.com/reference/iostream/stringstream/
atof()
(or
std::atof()
talking C++ - thanks jons34yp)