Abhishek
Abhishek

Reputation: 2673

atoi from string to Integer using char pointer

Here is the code I have written which splits a string in c and then I want to return the first integer value pointed by the char pointer.

#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);
} 

EDIT:It gives me segmentation fault.

The problem is it is printing 1853 as the year, But I want to convert this into integer format.How can i retrieve that value as an integer using the pointer?

Upvotes: 3

Views: 19382

Answers (3)

Johan Lundberg
Johan Lundberg

Reputation: 27038

you are here trying to use an integer as a string:

    printf("%s",value);

you should do

    printf("%d",value);

Edit: yes, and also do int value = atoi(ptr); as added in another answer.

main should also be int, not void.

Also, what compiler are you using? With gcc 4.6 I got these errors and warnings when trying to compile your code (after adding some includes):

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]

I'd think you could get at least some of these from most compilers.

Upvotes: 5

ugoren
ugoren

Reputation: 16441

Use:

int value = atoi(ptr);

atoi should get a character pointer, which is what ptr is. *ptr is the first character - 1 in this case, and anyway isn't a pointer, so it's unusable for atoi.

Upvotes: 0

kennytm
kennytm

Reputation: 523224

    int value = atoi(ptr);

No need to dereference, atoi() expects a const char*, not a char.

    printf("%d",value);

And you print an integer using %d or %i. %s is for string only.


BTW, maybe you would like to use strtol instead

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"

Upvotes: 3

Related Questions