Search code examples
catoi

pointer of char array to integer in c


This is my code:

char str[] ="";
scanf("%s",&str);
char * pch;
pch = strtok (str,"#");
printf ("%s\n",pch);
return 0;

I need to render an input of "1#2#3" to three integers first, second and third. My code above tackles only the first variable and prints the first string "1" but i want to save it to an int variable.

I tried:

int first = atoi(&pch)

But 'first' get's the value 0 instead of 1. How can i parse a pointer of an array char to int?


Solution

  • If you know the precise layout of the input, and the exact number of ints, you can simplify this greatly:

    scanf("%d#%d#%d", &a, &b, &c);
    

    Here is a link to a demo on ideone.