forked from jhpy1024/CProgrammingLanguageExercises
-
Notifications
You must be signed in to change notification settings - Fork 0
/
exercise_5-6.c
84 lines (66 loc) · 1.15 KB
/
exercise_5-6.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
#include <ctype.h>
#include <stdio.h>
#include <string.h>
int get_line(char* line, int max_line_length)
{
int length = 0;
while ((*line = getchar()) != '\n' && length <= max_line_length)
{
++length;
++line;
}
*line = '\0';
return length;
}
void reverse(char* str)
{
for (char* i = str, *j = str + strlen(str) - 1; i < j; ++i, --j)
{
char tmp = *i;
*i = *j;
*j = tmp;
}
}
void itoa(int value, char* str)
{
char* start_of_str = str;
int sign;
if ((sign = value) < 0)
{
value *= -1;
}
do
{
*str++ = value % 10 + '0';
}
while ((value /= 10) > 0);
if (sign < 0)
{
*str++ = '-';
}
*str = '\0';
reverse(start_of_str);
}
int atoi(char* str)
{
int value = 0;
int sign = (*str == '-' ? -1 : 1);
if (sign == -1)
{
++str;
}
for (; isdigit(*str); ++str)
{
value = value * 10 + (*str - '0');
}
return value * sign;
}
int main()
{
char* a = "-123";
char* b = "482";
int ia = atoi(a);
int ib = atoi(b);
printf("%d %d\n", ia, ib);
return 0;
}