Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pointer of char array to integer in c

Tags:

c

atoi

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?

like image 348
Tom Avatar asked May 20 '26 22:05

Tom


2 Answers

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.

like image 71
Sergey Kalinichenko Avatar answered May 22 '26 10:05

Sergey Kalinichenko


The code has undefined behaviour as str is not large enough to handle any input. str can hold at most 1 char and scanf() will append a null terminator when it reads in a string. If the user enters a single character and hits return then scanf() will write beyond the bounds the array str.

To correct, decide the maximum length of string that is acceptable and prevent scanf() by reading more:

char str[1024];
if (1 == scanf("%1023s", str))
{
}

Note that atoi() produces a result of 0 for invalid input or for "0", which is not helpful. Use strtol() instead or see the answer from dasblinkenlight for a simpler solution.

like image 34
hmjd Avatar answered May 22 '26 10:05

hmjd



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!