0

I am trying to read type double values from a char buffer word by word. In the file I have some values like 0.032 0.1234 8e-6 4e-3 etc. Here is my code which is using atof() function to convert word (stored in array 's') to a double value num :

char s[50];
double num;
while(getline(str, line))
{
    int i=0, j=0;
    while(line[i] != '\0')
    {
        if(line[i] != ' ')
        {
            s[j] = line[i];
            //cout << s[j];   <-- output of s[j] shows correct values (reading 'e' correctly)
            j++;
        }
        else
        {
            num = atof(s);
            cout << num << " ";
            j=0;
        }
        i++;
    }
    cout << endl;
}

Whenever numbers which include 'e' in them (like 8e-6) comes, atof() function just returns 0 for them. Output for above example values comes out to be 0.032 0.1234 0 0.

I tried to check with a demo array and there atof() worked fine.

char t[10];
    t[0] = '8';
    t[1] = 'e';
    t[2] = '-';
    t[3] = '5';
    t[4] = '\0';

    double td = atof(t);
    cout << "td = " << td << endl;

Here the output is td = 8e-05 I have included both <stdio.h> and <stdlib.h>. Any idea why it's not working?

Jaipreet
  • 45
  • 7
  • What answer are you expecting? – Alan Stokes Aug 27 '16 at 22:35
  • I am expecting `0.032 0.1234 8e-06 4e-03`. – Jaipreet Aug 27 '16 at 22:37
  • Please learn how to debug. It's simple and is the most important skill you need right now. – Amit Aug 27 '16 at 22:38
  • 3
    My curiosity is killing me. [**Why not just do this**](http://ideone.com/4OYZ9g) ? (I'm relying on this question being tagged C++, which it should *not* be if it is tagged C, and vice-versa). – WhozCraig Aug 27 '16 at 22:39
  • @user3121023 Thanks, it works now. – Jaipreet Aug 27 '16 at 22:39
  • Please update your question to show us your actual code. You define `s` and then refer to `str`, which is not defined. Show us a complete program that exhibits the problem, including any required `#include` directives and a definition of `main`. – Keith Thompson Aug 27 '16 at 22:40

1 Answers1

0

You have to pass into function atof() only a correct representaton of double, otherwise the return value is 0.

If you will check a very simple code char p[] = "6e-5"; double a = atof(p); you will see that it is working.

It means that you have a problem not with 6e-5 number iself, but with a wrong representation of you string s.

Slav
  • 35
  • 1
  • 9