开发者

like atoi but to float

开发者 https://www.devze.com 2023-02-11 07:49 出处:网络
Is there a function similar to atoi wh开发者_运维问答ich converts a string to float instead of to integer?atof()

Is there a function similar to atoi wh开发者_运维问答ich converts a string to float instead of to integer?


atof()

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


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


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


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


Use atof from stdlib.h:

double atof ( const char * str );


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


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


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

There's also strtod.


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消