从字符串解析小浮点数

C++ parsing small float from string

本文关键字:浮点数 字符串      更新时间:2023-10-16

我希望我的代码从文件中读取参数。文件中有这一行:

tol=1e-10

,我使用atof将其解析为浮点数:

double tol;
char * c = "1e-10"
tol=atof(c);

但是,它被解析为0而不是1e-10

Edit:事实证明它确实解析正确,很抱歉打扰了你们。我忘了printf默认不显示小值。我一开始就怀疑这一点,因为我的一张支票冻结了。

代码:

#include <iostream>
#include <cstdlib>
using namespace std;
int main() {
    double d = atof( "1e-10" );
    cout << d << endl;
}

打印1平台以及。

如何打印结果,确保点后面有很多数字。可能是舍入错误

问题是std::atof()在发生错误时返回0,因此您无法将两者区分开来。

既然这是一个c++问题,为什么不使用流呢?像这样:

double get_tol(std::istream& is)
{
  std::string key;
  if( !is>>key || key!="tol" ) throw "You need error handling here!";
  char equal;
  if( !is>>equal || equal!='=' ) throw "You need error handling here!";
  double d;
  if( !is>>d )throw "You need error handling here!";
  return d;
}

c转换为std::string并使用stringstream