-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathstr_to_i().c
53 lines (48 loc) · 1.15 KB
/
str_to_i().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
//program to convert integer to string and string to integer
#include <stdio.h>
#include <ctype.h>
int str_to_i(char str[])
{
int i, num = 0, sign;
i = 0;
while (isspace(str[i])) //skip isspace
i++;
sign = (str[i] == '-') ? -1 : 1;
if (str[i] == '-' || str[i] == '+')
i++;
while (isdigit(str[i]))
num = num * 10 + (str[i++] - '0');
return sign * num;
}
double str_to_d(char str[])
{
int i, j, sign;
double num = 0;
i = 0;
while (isspace(str[i])) //skip isspace
i++;
sign = (str[i] == '-') ? -1 : 1;
if (str[i] == '-' || str[i] == '+')
i++;
while (isdigit(str[i]))
num = num * 10 + (str[i++] - '0');
if (str[i] == '.')
i++;
j = i;
while (isdigit(str[i]))
num = num * 10 + (str[i++] - '0');
return sign * num / pow(10, i - j);
}
int main(void)
{
char str[20];
printf("Enter a string : ");
gets(str);
puts(str);
printf("%d\n", str_to_i(str));
printf("\n\nEnter a string : ");
gets(str);
puts(str);
printf("%lf\n", str_to_d(str));
return 0;
}