2012-01-29 4 views
3

다음은 C에서 문자열을 분할 한 다음 char 포인터가 가리키는 첫 번째 정수 값을 반환하고자하는 코드입니다.atoi에서 char 포인터를 사용하는 정수

#include<stdio.h> 
void main(){ 
    int month[12]={0}; 
    char buf[]="1853 was the year"; 
     char *ptr; 
     ptr = strtok(buf," "); 
     printf("%s\n",ptr); 
     int value = atoi(*ptr); 
     printf("%s",value); 
} 

편집 : 세그먼트 오류가 발생합니다.

문제는 1853 년으로 인쇄하는 것입니다.하지만 이것을 정수 형식으로 변환하고 싶습니다. 포인터를 사용하여 정수로 그 값을 검색 할 수 있습니까?

printf("%s",value); 

당신이해야

printf("%d",value); 

편집 :

+0

참고 : strtonum은 atoi/atol의 '안전하고 강력한'버전입니다. – Finslicer

+0

주 :'main()'은'int'를 반환하고'(void)'또는'(int, char **)'를 사용합니다. – unwind

답변

4
여기에 문자열로 정수를 사용하려고

예, 또한 int 값 = atoi 함수 (PTR) 할; 다른 대답으로 추가되었습니다.

주 또한 무효가 아닌 int 여야합니다.

또한 어떤 컴파일러를 사용하고 있습니까?

ptrbla.C:5:11: error: ‘::main’ must return ‘int’ 
ptrbla.C: In function ‘int main()’: 
ptrbla.C:11:30: error: invalid conversion from ‘char’ to ‘const char*’ [-fpermissive] 
/usr/include/stdlib.h:148:12: error: initializing argument 1 of ‘int atoi(const char*)’ [-fpermissive] 
ptrbla.C:12:26: warning: format ‘%s’ expects argument of type ‘char*’, but argument 2 has type ‘int’ [-Wformat] 

을 나는 대부분의 컴파일러에서 이들 중 적어도 일부를 얻을 수 있다고 생각 것 : (추가 한 후 일부 포함) 코드를 컴파일 할 때 gcc가 4.6으로 나는이 오류와 경고를 받았습니다.

2
int value = atoi(ptr); 

역 참조 할 필요가 atoi()const char* 아닌 char 기대하고있다.

printf("%d",value); 

는 그리고 당신은 %d 또는 %i를 사용하여 정수를 인쇄 할 수 있습니다. %s은 문자열 전용입니다.


BTW, 어쩌면 당신은 strtol을 사용하고자하는 대신

char buf[]="1853 was the year"; 
char* next; 
long year = strtol(buf, &next, 10); 

printf("'%ld' ~ '%s'\n", year, next); 
// 'year' is 1853 
// 'next' is " was the year" 
+0

8 초 후에 나에게,하지만 더 완전한 대답. – ugoren

0

사용 :

int value = atoi(ptr); 

atoiptr이 무엇 인 문자 포인터를 얻어야한다. *ptr이 첫 번째 문자입니다.이 경우 1이며 어쨌든 포인터가 아니므로 atoi에서는 사용할 수 없습니다.

관련 문제