eric@ee.ualberta.ca (Eric Norum) (04/07/91)
Consider the following program fragment: #include <stdlib.h> #include <stdio.h> . . char *cp, *ptr; double x; . . cp = "trash" x = strtod(cp, &ptr); From the description of strtod: If the value of ptr is not (char **)NULL, the variable to which it points is set to point at the character after the last number, if any, that was recognized. If no number can be formed, *ptr is set to str, and zero is returned. The strtod supplied with NextStep 2.0 does not behave as expected. It returns a zero and `ptr' is set to point at the '\0' at the end of the `trash' string indicating a valid number was converted. This is most annoying. I use strtod instead of atof because strtod is supposed to return an indication of invalid data. Has anyone got a fix for this? -- Eric Norum Dept. of Electrical Engineering eric@ee.ualberta.ca University of Alberta Edmonton, Canada. phone: (403) 492-4626
hamachi@tabasco (Gordon Hamachi) (04/09/91)
Here's a workaround for your problem with strtod(): You can use sscanf() with the %n option to figure out how much of your input has been consumed, and then do pointer arithmetic to get the correct value for ptr. But... The %n option doesn't work correctly when the input string is completely consumed--the corresponding integer arg is not changed. The workaround for THIS problem is to initialize the integer arg to the input string length. It will be changed IFF the input is not completely consumed: int charsUsed=strlen((char *) s; double doubleValue; if(sscanf((char *) s, "%F%n", &doubleValue, &charsUsed)) Eric Norum writes > The strtod supplied with NextStep 2.0 does not behave as expected. > It returns a zero and `ptr' is set to point at the '\0' at the end > of the `trash' string indicating a valid number was converted. > > This is most annoying. I use strtod instead of atof because strtod > is supposed to return an indication of invalid data. Has anyone got > a fix for this?