Algorithms_in_C 1.0.0
Set of algorithms implemented in C.
Loading...
Searching...
No Matches
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
 
void test_c_atoi ()
 test the function implementation
 
int main (int argc, char **argv)
 the main function take one argument of type char* example : .
 

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 {
34 sign = -1;
35 i++;
36 }
37 else if (str[i] == '+')
38 {
39 sign = 1;
40 i++;
41 }
42
43 /* converting char by char to a numeric value */
44 while (str[i] >= 48 && str[i] <= 57 && str[i] != '\0')
45 {
46 prev = value;
47 value = value * 10 + sign * (str[i] - '0');
48
49 /* managing the overflow */
50 if (sign == 1 && prev > value)
51 return (-1);
52 else if (sign == -1 && prev < value)
53 return (0);
54 i++;
55 }
56 return (value);
57}
double sign(double a, double b)
Function to check if two input values have the same sign (the property of being positive or negative)
Definition bisection_method.c:32
Here is the call graph for this function:

◆ main()

int main ( int  argc,
char **  argv 
)

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

/program 123

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

◆ test_c_atoi()

void test_c_atoi ( )

test the function implementation

63{
64 printf("<<<< TEST FUNCTION >>>>\n");
65 assert(c_atoi("123") == atoi("123"));
66 assert(c_atoi("-123") == atoi("-123"));
67 assert(c_atoi("") == atoi(""));
68 assert(c_atoi("-h23") == atoi("-h23"));
69 assert(c_atoi(" 23") == atoi(" 23"));
70 assert(c_atoi("999999999") == atoi("999999999"));
71 printf("<<<< TEST DONE >>>>\n");
72}
Here is the call graph for this function: