like atoi but to float

2019-03-25 04:41发布

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

标签: c++ casting atoi
11条回答
Animai°情兽
2楼-- · 2019-03-25 04:45

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

查看更多
beautiful°
3楼-- · 2019-03-25 04:46

Use atof from stdlib.h:

double atof ( const char * str );
查看更多
戒情不戒烟
4楼-- · 2019-03-25 04:48

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

查看更多
唯我独甜
5楼-- · 2019-03-25 04:49

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楼-- · 2019-03-25 04:51

atof()

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

查看更多
Lonely孤独者°
7楼-- · 2019-03-25 04:58

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

查看更多
登录 后发表回答