skylerl
skylerl

Reputation: 4180

strtod is returning 0

I've been working on this project that deals with an input file that looks like the following:

A 0.0345
B 0.3945
...
Z 0.2055

Basically, I'm reading each line, after reading the line, I want to pull only the double out of the string. I'm trying to use strtod() and everyone's examples seem to use it perfectly fine but in my example, it only returns 0.

Here is my code:

for (count = 0; count < 26; count++)
{
    char buffer[100]; /* Buffer for the line read by fgets */
    char *letters; /* Stores the string calculated by strtod */
    double relFreq = 0.0;

    if (fgets(buffer, 100, stream) != NULL)
    {
        relFreq = (double)strtod(buffer, &letters); /* Since the format is A 0.0000, we're just grabbing the double */
        *(sampleOne + count) = relFreq; /* Add the relFreq to the array */
    }
}

Through the use of a debugger, buffer has the correct data, for instance A 0.0345\n but when strtod() returns a value it's always 0. Any help would be appreciated!

Upvotes: 2

Views: 1603

Answers (3)

Vlad from Moscow
Vlad from Moscow

Reputation: 311038

You could use sscanf. For example

#include <stdio.h>

int main(void) 
{
    char *s = "A 0.0345\n";

    char c;
    double d;

    sscanf( s, "%c %lf", &c, &d );

    printf( "%f\n", d );

    return 0;
}

The output os

0.034500

As for your code then you could at first to find a digit in the buffer and apply function strtod to the pointer that points to the found digit provided that the first field in the buffer is always a non-digit.

Upvotes: 1

Sean Bright
Sean Bright

Reputation: 120654

I'm not sure why you think that strtod will ignore the leading letter on your lines, but it will not. You'll need to do something like this:

relFreq = (double) strtod(&buffer[1], &letters);

And since you are not using letters:

relFreq = (double) strtod(&buffer[1], NULL); 

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726659

Since the first character is non-numeric, strtod should be returning letters equal to buffer (the first character is invalid), indicating that nothing has been read.

You should be able to fix this by passing &buffer[2], where the number starts:

relFreq = strtod(&buffer[2], &letters);

Demo.

Upvotes: 2

Related Questions