Created
April 9, 2017 17:55
-
-
Save makiftasova/d680fcfe21acb519f5c210c29dac62d4 to your computer and use it in GitHub Desktop.
This file contains hidden or 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> /* printf, fgets */ | |
#include <stdlib.h> /* atoi */ | |
#include <string.h> | |
/** | |
* atoi_r : a wrapper for atoi. | |
* atoi from stdlib.h has undefined behaviour if input does not contain | |
* a valid integer value. this function handles that undefined behaviour | |
* for non negative integers. | |
* | |
*/ | |
int atoi_r(const char *str); | |
int main(int argc, char **argv){ | |
const char * str0 = "12312313", *str1="asd"; | |
printf("%d\n", atoi_r(str0)); | |
printf("%d\n", atoi_r(str1)); | |
return 0; | |
} | |
int atoi_r(const char *str){ | |
char c; | |
for(size_t i = 0; i < strlen(str); ++i){ | |
if ('0' > str[i] || str[i] > '9') | |
return -1; | |
} | |
return atoi(str); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment