eye_water
eye_water

Reputation: 107

A simple strtod() example in c

When I read strtod() example , I have some doubt. Here is the code:

const char *p = "111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz";
printf("Parsing '%s':\n", p);
char *end;
double f; 
for (f = strtod(p, &end); p != end; f = strtod(p, &end))
{
    printf("'%.*s' -> ", (int)(end-p), p);//I can't understand this line
    p = end;
    if (errno == ERANGE){
        printf("range error, got ");
        errno = 0;
    }
    printf("%f\n", f);
}

Output:

Parsing '111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz':
'111.11' -> 111.110000
' -2.22' -> -2.220000
' Nan' -> 1.#QNAN0
' nan(2)' -> 1.#SNAN0
' inF' -> 1.#INF00
' 0X1.BC70A3D70A3D7P+6' -> 111.110000
'  1.18973e+4932' -> range error, got 1.#INF00

Why can end - p get a value?

Upvotes: 2

Views: 1345

Answers (1)

Barmar
Barmar

Reputation: 781255

strtod(p, &end) sets end to point to the next byte after the number that was parsed. So when you make this call with the initial string, the result is:

111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz
^     ^
p    end

end-p is then the length of the number that was parsed. When you write

printf("'%.*s' -> ", (int)(end-p), p);

this length is used for the .* size of the %s field, which makes it only print that many bytes of the string.

The loop then sets p = end and repeats, so this time you get:

111.11 -2.22 Nan nan(2) inF 0X1.BC70A3D70A3D7P+6  1.18973e+4932zzz
      ^     ^
      p    end

The loop keeps doing this to find each number in the string. If it can't parse a number at the location in the string, it sets end to point to the input string, and the test p != end fails, so the loop ends.

Upvotes: 3

Related Questions