Algorithms_in_C  1.0.0
Set of algorithms implemented in C.
c_atoi_str_to_integer.c File Reference

Recoding the original atoi function in stdlib.h. More...

#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
Include dependency graph for c_atoi_str_to_integer.c:

Functions

int c_atoi (const char *str)
 the function take a string and return an integer More...
 
void test_c_atoi ()
 test the function implementation
 
int main (int argc, char **argv)
 the main function take one argument of type char* example : . More...
 

Detailed Description

Recoding the original atoi function in stdlib.h.

Author
Mohammed YMIKW The function convert a string passed to an integer

Function Documentation

◆ c_atoi()

int c_atoi ( const char *  str)

the function take a string and return an integer

Parameters
[out]strpointer to a char address
17 {
18  int i;
19  int sign;
20  long value;
21  long prev;
22 
23  i = 0;
24  sign = 1;
25  value = 0;
26 
27  /* skipping the spaces */
28  while (((str[i] <= 13 && str[i] >= 9) || str[i] == 32) && str[i] != '\0')
29  i++;
30 
31  /* store the sign if it is negative sign */
32  if (str[i] == '-')
33  sign = -1;
34  else if (str[i] == '+')
35  sign = 1;
36 
37  /* converting char by char to a numeric value */
38  while (str[i] >= 48 && str[i] <= 57 && str[i] != '\0')
39  {
40  prev = value;
41  value = value * 10 + sign * (str[i] - '0');
42 
43  /* managing the overflow */
44  if (sign == 1 && prev > value)
45  return (-1);
46  else if (sign == -1 && prev < value)
47  return (0);
48  i++;
49  }
50  return (value);
51 }

◆ main()

int main ( int  argc,
char **  argv 
)

the main function take one argument of type char* example : .

/program 123

73 {
74  test_c_atoi();
75 
76  if (argc == 2)
77  {
78  printf("Your number + 5 is %d\n", c_atoi(argv[1]) + 5);
79  return (0);
80  }
81  printf("wrong number of parmeters\n");
82  return (1);
83 }
Here is the call graph for this function:
c_atoi
int c_atoi(const char *str)
the function take a string and return an integer
Definition: c_atoi_str_to_integer.c:16
test_c_atoi
void test_c_atoi()
test the function implementation
Definition: c_atoi_str_to_integer.c:56