Created
November 20, 2013 19:10
-
-
Save ACEfanatic02/7569101 to your computer and use it in GitHub Desktop.
Quick demo using strtod.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdlib.h> | |
#include <stdio.h> | |
/* | |
Example Usage: | |
char * str = getString(); | |
double val; | |
if (tryParseDouble(str, &val)) { | |
doSomethingWith(val); | |
} | |
*/ | |
int tryParseDouble(char * str, double * rv) | |
{ | |
if (str == NULL || rv == NULL) { | |
return 0; | |
} | |
char * end = NULL; | |
double d = strtod(str, &end); | |
if (end == str) { | |
// No characters consumed. | |
return 0; | |
} | |
else { | |
*rv = d; | |
return 1; | |
} | |
} | |
int main(int argc, char const *argv[]) | |
{ | |
char * strs[] = { | |
"-100.7", | |
"+10e-4", | |
"+", | |
"notadouble", | |
}; | |
double d; | |
int i; | |
for (i = 0; i < 4; ++i) { | |
if (tryParseDouble(strs[i], &d)) { | |
printf("%d: %s -> %f\n", i, strs[i], d); | |
} | |
else { | |
printf("%d: %s is not a double.\n", i, strs[i]); | |
} | |
} | |
return 0; | |
} | |
// $ make sdtest | |
// $ ./sdtest | |
// 0: -100.7 -> -100.700000 | |
// 1: +10e-4 -> 0.001000 | |
// 2: + is not a double. | |
// 3: notadouble is not a double. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment