STUDY/자료구조(Data Structures)

자료구조 •String 숫자를 Int로 변환(스트링->정수 변환)•

Yeonzel 2017. 12. 30. 12:56

String 숫자를 Int로 변환(스트링->정수 변환)

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
#include <stdio.h>
 
char str[101];
int result;
 
int atoi(const char *str)
{
    int v = 0, cnt, digit;
    while ((cnt = *str++!= '\0')
    {
        if (cnt >= '0' && cnt <= '9')
            digit = cnt - '0';
        else
            break;
        v = (v * 10+ digit;
    }
    return v;
}
 
int main()
{
    result = 0;
    scanf("%s", str);
    result = atoi(str);
    printf("%d\n", result);
}
cs