-->

like atoi but to float

2019-03-25 04:40发布

问题:

Is there a function similar to atoi which converts a string to float instead of to integer?

回答1:

atof()

(or std::atof() talking C++ - thanks jons34yp)



回答2:

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++.



回答3:

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;
}


回答4:

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.)



回答5:

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>)



回答6:

Use atof from stdlib.h:

double atof ( const char * str );


回答7:

Prefer strtof(). atof() does not detect errors.



回答8:

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



回答9:

#include <stdlib.h>
double atof(const char*);

There's also strtod.



回答10:

Try boost::spirit: fast, type-safe and very efficient:

std::string::iterator begin = input.begin();
std::string::iterator end = input.end();
using boost::spirit::float_;

float val;
boost::spirit::qi::parse(begin,end,float_,val);


回答11:

As an alternative to all above, you may use string stream. http://cplusplus.com/reference/iostream/stringstream/



标签: c++ casting atoi