From 32c725603f912448a6ac12a9405d4c2e002304c0 Mon Sep 17 00:00:00 2001 From: Mohammed YMIK Date: Fri, 12 Jun 2020 14:56:57 +0100 Subject: [PATCH] add atoi that convert string to integer --- conversions/c_atoi_str_to_integer.c | 40 +++++++++++++++++++++++++++++ 1 file changed, 40 insertions(+) create mode 100644 conversions/c_atoi_str_to_integer.c diff --git a/conversions/c_atoi_str_to_integer.c b/conversions/c_atoi_str_to_integer.c new file mode 100644 index 00000000..ac9cc81e --- /dev/null +++ b/conversions/c_atoi_str_to_integer.c @@ -0,0 +1,40 @@ +#include + +// recoding the original atoi function in stdlib.h +int c_atoi(char *str) +{ + int i; + int sign; + long value; + long prev; + + i = 0; + sign = 1; + value = 0; + // skip wait spaces + while (((str[i] <= 13 && str[i] >= 9) || str[i] == 32) && str[i] != '\0') + i++; + // store the sign + if (str[i] == '-' || str[i] == '+') + (str[i++] == '-') ? sign = -1 : 1; + // convert char by char to an int value + while (str[i] >= 48 && str[i] <= 57 && str[i] != '\0') + { + prev = value; + value = value * 10 + sign * (str[i] - '0'); + // manage the overflow + if (sign == 1 && prev > value) + return (-1); + else if (sign == -1 && prev < value) + return (0); + i++; + } + return (value); +} + + +int main() +{ + // Test + printf("%d\n", c_atoi("-234")); +}