Created
December 3, 2014 22:50
-
-
Save oz123/1973b9b4c9ef6356bc8f to your computer and use it in GitHub Desktop.
Detect if a string is an integer or a double number
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 <stdio.h> | |
#include <stdlib.h> | |
#include <string.h> | |
#include <errno.h> | |
int main(int argc, char *argv[]) | |
{ | |
char* to_convert = argv[1]; | |
char* p = NULL; | |
errno = 0; | |
long val = strtol(argv[1], &p, 0); | |
if (errno != 0) | |
return 1;// conversion failed (EINVAL, ERANGE) | |
if (to_convert == p){ | |
// conversion to int failed (no characters consumed) | |
double val2 = strtod(p, &p); | |
if (*p){ | |
printf("Not a number!\n"); | |
return 1; | |
} | |
printf("Double %lf\n" , val2); | |
return 0; | |
} | |
if (*p != 0){ | |
// conversion to int failed (trailing data) | |
double val2 = strtod(argv[1], &p); | |
if (*p){ | |
printf("Not a number!\n"); | |
return 1; | |
} | |
printf("Double %lf\n" , val2); | |
return 0; | |
} | |
printf("Int %ld\n" , val); | |
return 0; | |
} | |
/* | |
$ ./a.out 123 | |
Int 123 | |
$ ./a.out -123 | |
Int -123 | |
$ ./a.out 31.1 | |
Double 31.100000 | |
$ ./a.out -231 | |
Int -231 | |
$ ./a.out NaN | |
Double nan | |
$ ./a.out -Nan | |
Double nan | |
$ ./a.out -INF | |
Double -inf | |
$ ./a.out INF | |
Double inf | |
$ ./a.out 12.3 | |
Double 12.300000 | |
$ ./a.out -12,3 | |
Not a number! | |
$ ./a.out -12.3 | |
Double -12.300000 | |
$ ./a.out foo | |
Not a number! | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment