-
Notifications
You must be signed in to change notification settings - Fork 2
/
convert string to int.c
86 lines (66 loc) · 1.37 KB
/
convert string to int.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
85
86
#include <stdio.h>
#include <stdlib.h>
int lenstr(char s[]) {
int c = 0;
while (s[c] != '\0')
c++;
return c;
}
int convert_int(char str[]){
int n=0,i=0,strln=lenstr(str);
while (i<strln) {
n*=10;
switch (str[i]) {
case '1':
n+=1;
i+=1;
break;
case '2':
i+=1;
n+=2;
break;
case '3':
n+=3;
i+=1;
break;
case '4':
n+=4;
i+=1;
break;
case '5':
n+=5;
i+=1;
break;
case '6':
n+=6;
i+=1;
break;
case '7':
n+=7;
i+=1;
break;
case '8':
n+=8;
i+=1;
break;
case '9':
n+=9;
i+=1;
break;
case '0':
n+=0;
i+=1;
break;
default:
return -1;
break;
}
}
return n;
}
int main(void) {
char str[10] = "2344";
int x = convert_int(str);
printf("Converting %s: %d\n",str, x);
return 0;
}