16

是否有类似于 atoi 的函数将字符串转换为浮点数而不是整数?

4

11 回答 11

24

atof()

(或者std::atof()说 C++ - 谢谢jons34yp

于 2011-02-16T13:28:31.043 回答
17
boost::lexical_cast<float>(str);

这个模板函数包含在流行的Boost库集合中,如果你对 C++ 很认真,你会想要了解它。

于 2011-02-16T13:31:43.507 回答
17

将字符串转换为任何类型(默认可构造和可流式传输):

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;
}
于 2011-02-16T13:37:12.020 回答
6

strtof

从手册页

strtod()、strtof() 和 strtold() 函数将 nptr 指向的字符串的初始部分分别转换为 double、float 和 long double 表示形式。

字符串(的初始部分)的预期形式是可选的前导空格,如 isspace(3) 所识别,可选的加号 (''+'') 或减号 (''-''),然后是 (i ) 十进制数,或 (ii) 十六进制数,或 (iii) 无穷大,或 (iv) NAN(非数字)。

/手册页>

atof 将字符串转换为双精度(不是顾名思义的浮点数。)

于 2011-02-16T13:29:26.120 回答
6

作为已经提到的std::strtof()and的替代方案,boost::lexical_cast<float>()引入了新的 C++ 标准

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

用于错误检查字符串到浮点的转换。GCC 和 MSVC 都支持它们(记住#include <string>

于 2011-02-16T13:59:53.267 回答
1

使用atof来自stdlib.h

double atof ( const char * str );
于 2011-02-16T13:29:34.903 回答
1

更喜欢strtof(). atof()不检测错误。

于 2011-02-16T13:30:42.857 回答
1

这也可以(但 C 类型的代码):

#include <iostream>

using namespace std;

int main()
{
float myFloatNumber = 0;
string inputString = "23.2445";
sscanf(inputString.c_str(), "%f", &myFloatNumber);
cout<< myFloatNumber * 100;

}

在这里看到它:http: //codepad.org/qlHe5b2k

于 2011-02-16T14:02:53.047 回答
0
#include <stdlib.h>
double atof(const char*);

还有strtod

于 2011-02-16T13:28:51.097 回答
0

尝试 boost::spirit:快速、类型安全且非常高效:

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);
于 2011-02-16T15:19:20.717 回答
-1

作为上述所有方法的替代方案,您可以使用字符串流。 http://cplusplus.com/reference/iostream/stringstream/

于 2011-02-16T14:58:55.077 回答