2020-06-12 18:11:41 +03:00
|
|
|
/**
|
|
|
|
* \file
|
2020-06-20 14:28:26 +03:00
|
|
|
* \brief Recoding the original atoi function in stdlib.h
|
2020-06-12 18:53:37 +03:00
|
|
|
* \author [Mohammed YMIK](https://github.com/medymik)W
|
2020-06-20 14:28:26 +03:00
|
|
|
* The function convert a string passed to an integer
|
2020-06-12 18:11:41 +03:00
|
|
|
*/
|
|
|
|
#include <assert.h>
|
2020-06-20 14:28:26 +03:00
|
|
|
#include <stdio.h>
|
2020-06-12 18:11:41 +03:00
|
|
|
#include <stdlib.h>
|
|
|
|
#include <string.h>
|
2020-06-12 16:56:57 +03:00
|
|
|
|
2020-06-12 18:11:41 +03:00
|
|
|
/**
|
|
|
|
* the function take a string and return an integer
|
|
|
|
* \param[out] str pointer to a char address
|
|
|
|
*/
|
|
|
|
int c_atoi(const char *str)
|
2020-06-12 16:56:57 +03:00
|
|
|
{
|
2020-06-20 14:28:26 +03:00
|
|
|
int i;
|
|
|
|
int sign;
|
|
|
|
long value;
|
|
|
|
long prev;
|
2020-06-12 18:11:41 +03:00
|
|
|
|
|
|
|
i = 0;
|
|
|
|
sign = 1;
|
|
|
|
value = 0;
|
|
|
|
|
|
|
|
/* skipping the spaces */
|
|
|
|
while (((str[i] <= 13 && str[i] >= 9) || str[i] == 32) && str[i] != '\0')
|
|
|
|
i++;
|
|
|
|
|
|
|
|
/* store the sign if it is negative sign */
|
|
|
|
if (str[i] == '-' || str[i] == '+')
|
|
|
|
(str[i++] == '-') ? sign = -1 : 1;
|
|
|
|
|
|
|
|
/* converting char by char to a numeric value */
|
|
|
|
while (str[i] >= 48 && str[i] <= 57 && str[i] != '\0')
|
|
|
|
{
|
|
|
|
prev = value;
|
|
|
|
value = value * 10 + sign * (str[i] - '0');
|
|
|
|
|
|
|
|
/* managing the overflow */
|
|
|
|
if (sign == 1 && prev > value)
|
|
|
|
return (-1);
|
|
|
|
else if (sign == -1 && prev < value)
|
|
|
|
return (0);
|
|
|
|
i++;
|
|
|
|
}
|
2020-06-20 14:28:26 +03:00
|
|
|
return (value);
|
2020-06-12 18:11:41 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* test the function implementation
|
|
|
|
*/
|
|
|
|
int test_c_atoi()
|
|
|
|
{
|
|
|
|
printf("<<<< TEST FUNCTION >>>>\n");
|
|
|
|
assert(c_atoi("123") == atoi("123"));
|
|
|
|
assert(c_atoi("-123") == atoi("-123"));
|
|
|
|
assert(c_atoi("") == atoi(""));
|
|
|
|
assert(c_atoi("-h23") == atoi("-h23"));
|
|
|
|
assert(c_atoi(" 23") == atoi(" 23"));
|
|
|
|
assert(c_atoi("999999999999") == atoi("999999999999"));
|
|
|
|
printf("<<<< TEST DONE >>>>\n");
|
2020-06-12 16:56:57 +03:00
|
|
|
}
|
|
|
|
|
2020-06-12 18:11:41 +03:00
|
|
|
/**
|
|
|
|
* the main function take one argument of type char*
|
|
|
|
* example : ./program 123
|
|
|
|
*/
|
2020-06-20 14:28:26 +03:00
|
|
|
int main(int argc, char **argv)
|
2020-06-12 16:56:57 +03:00
|
|
|
{
|
2020-06-12 18:11:41 +03:00
|
|
|
if (argc == 2)
|
|
|
|
{
|
|
|
|
printf("Your number + 5 is %d\n", c_atoi(argv[1]) + 5);
|
|
|
|
return (0);
|
|
|
|
}
|
|
|
|
printf("wrong number of parmeters\n");
|
|
|
|
return (1);
|
2020-06-12 16:56:57 +03:00
|
|
|
}
|