Add doc, signature, indentation

This commit is contained in:
Mohammed YMIK 2020-06-12 16:11:41 +01:00
parent 32c725603f
commit 18c677d6a5

View File

@ -1,40 +1,87 @@
/**
* \file
* \brief Recoding the original atoi function in stdlib.h
* \author [Krishna Vedala](https://github.com/kvedala)
*
* The function convert a string passed to an integer
*/
#include <stdio.h> #include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include <string.h>
// recoding the original atoi function in stdlib.h /**
int c_atoi(char *str) * the function take a string and return an integer
* \param[out] str pointer to a char address
*/
int c_atoi(const char *str)
{ {
int i; /**
int sign; * i is a counter
long value; * sign hold the sign (negative or positive)
long prev; * value hold the current value by default set to 0
* prev hold the previous value for managing the overflow
*/
int i;
int sign;
long value;
long prev;
i = 0; i = 0;
sign = 1; sign = 1;
value = 0; value = 0;
// skip wait spaces
while (((str[i] <= 13 && str[i] >= 9) || str[i] == 32) && str[i] != '\0') /* skipping the spaces */
i++; while (((str[i] <= 13 && str[i] >= 9) || str[i] == 32) && str[i] != '\0')
// store the sign i++;
if (str[i] == '-' || str[i] == '+')
(str[i++] == '-') ? sign = -1 : 1; /* store the sign if it is negative sign */
// convert char by char to an int value if (str[i] == '-' || str[i] == '+')
while (str[i] >= 48 && str[i] <= 57 && str[i] != '\0') (str[i++] == '-') ? sign = -1 : 1;
{
prev = value; /* converting char by char to a numeric value */
value = value * 10 + sign * (str[i] - '0'); while (str[i] >= 48 && str[i] <= 57 && str[i] != '\0')
// manage the overflow {
if (sign == 1 && prev > value) prev = value;
return (-1); value = value * 10 + sign * (str[i] - '0');
else if (sign == -1 && prev < value)
return (0); /* managing the overflow */
i++; if (sign == 1 && prev > value)
} return (-1);
return (value); else if (sign == -1 && prev < value)
return (0);
i++;
}
return (value);
}
/**
* 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");
} }
int main() /**
* the main function take one argument of type char*
* example : ./program 123
*/
int main(int argc, char **argv)
{ {
// Test if (argc == 2)
printf("%d\n", c_atoi("-234")); {
printf("Your number + 5 is %d\n", c_atoi(argv[1]) + 5);
return (0);
}
printf("wrong number of parmeters\n");
return (1);
} }