Yotam
Yotam

Reputation: 10685

C++ parsing small float from string

I want my code to read parameters in from a file. I have this line in that file:

tol=1e-10

and I use atof to parse this into a float:

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

However, it is parsed as 0 instead of 1e-10.

Edit: It turns out that it does parse correctly, I'm sorry to have bothered you guys. I forgot that printf doesn't show small values by default. I suspected this at the first place since one of my checks froze.

Upvotes: 2

Views: 2052

Answers (4)

sbi
sbi

Reputation: 224119

The problem is that std::atof() returns 0 in case of an error, so you can't tell the two apart.

Since this is a C++ question, why don't you use streams? Something like this:

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

Upvotes: 1

jonsca
jonsca

Reputation: 10381

Convert c into a std::string and use a stringstream instead.

Upvotes: 0

user2100815
user2100815

Reputation:

This code:

#include <iostream>
#include <cstdlib>
using namespace std;

int main() {
    double d = atof( "1e-10" );
    cout << d << endl;
}

prints 1e-10.

Upvotes: 3

ColWhi
ColWhi

Reputation: 1077

How are you printing the result, make sure you have lots of numbers after the point. It may be a rounding error.

Upvotes: 2

Related Questions