質問

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?

役に立ちましたか?

解決

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.

他のヒント

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.

You pass a char* to atoi(), not a char**. Just call it as atoi(pch)

You have declared str as char str[] ="";. This would allocate only one byte to str. Is it working correctly. I hope I am not missing something here.
As for strtok, you need to use it in a while loop
pch = strtok (str,"#");
while (pch != NULL)
{
printf ("%s\n",pch);
pch = strtok (NULL, "#");
}

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top