Recoding the original atoi function in stdlib.h.
More...
#include <assert.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
|
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 : .
|
|
Recoding the original atoi function in stdlib.h.
- Author
- Mohammed YMIKW The function convert a string passed to an integer
◆ c_atoi()
int c_atoi |
( |
const char * |
str | ) |
|
the function take a string and return an integer
- Parameters
-
[out] | str | pointer to a char address |
17{
18 int i;
20 long value;
21 long prev;
22
23 i = 0;
25 value = 0;
26
27
28 while (((str[i] <= 13 && str[i] >= 9) || str[i] == 32) && str[i] != '\0')
29 i++;
30
31
32 if (str[i] == '-')
33 {
35 i++;
36 }
37 else if (str[i] == '+')
38 {
40 i++;
41 }
42
43
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
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
◆ 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
◆ 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}