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)?
Printable View
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! */;
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 :)
Fine! :p
How about this?
You really are doing your best to thwart my optimization, aren't you? :pCode:if (d == 0 && strcmp(buf, "0") != 0 && strcmp(buf, "-0") != 0) /* Not a double! */;
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
I suppose... I'm used to atof/atod/atoi, which only takes one. Hmmm.
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.
That should work fine, too.Code:char* pEnd;
double d = strtod(buf, &pEnd);
if (pEnd - buf == 0) /* "Not a double!" */;
Not sure I get what you mean with strcmp won't work since d will ONLY be 0 if the user entered "0" or "-0" or a non-string, so what's the error?
I'm assuming it's part of a stream.
I'm beginning to have brain problems... :p
Still unsure :o
How do you expect it to fail? Example, please?
Unless it's part of your "problems"? ;)
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.
That is correct. I'm working on some logic to validate a double now. Stay tuned. ;)
Todd