I assume buf is your buffer - the string you read from the user:
Null as in NULL?Code:char buf[255]; fgets(buf, sizeof(buf), stdin);
Like if (p == NULL)?
Ah I see. Thanks for the explanation. I was thinking of just strtod.
However, if I may:?Code:if ( strtod(buf, NULL) == 0 && (buf[0] != '0' && ((buf[0] != '\0') && buf[0] != '-' && buf[1] != '0')) ) /* Not a double! */;
Last edited by robwhit; 01-14-2008 at 03:50 PM.
Ely
does the same function works for floats also as well?
Well, just call me a fly in the ointment.
This will fail the test and be called valid: 0DLFKD
It converts to zero since it's garbage, and the first char is zero, so it would be accepted.
I know, I know. I'm just stirring the pot.
Todd
Really, to get the most out of strtod you have to take advantage of all of it's arguments. Knowing where strtod stopped its conversion helps you decide what is acceptable and not acceptable input. Dave Sinkula has illustrated the proper technique in a series of snippets.
My understanding is that strtod works for floats just fine:
float fltpt = (float) strtod( example, &endpt );
http://www.daniweb.com/code/snippet597.html
Last edited by whiteflags; 01-14-2008 at 03:55 PM.
Ah you caught my post before I saw my error....
the strcmp won't work because there might be more characters afterwards.
lol we are such a waste of bandwidth.
I'm assuming it's part of a stream.
I'm beginning to have brain problems...
Last edited by robwhit; 01-14-2008 at 04:09 PM.
for example, you read in a buffer from a file:
char buf[128];
fread(buf, sizeof(buf), 1, file);
then you try to see if it contains a double.
oops, what if there is more data than the double? It will not have a \0, and so it will not compare equal.
Last edited by robwhit; 01-14-2008 at 04:17 PM.
That is correct. I'm working on some logic to validate a double now. Stay tuned.
Todd