I want to split a numeric string into separate numbers and then store each number in an integer array.
For example we have this numeric string: 1 2 3
and I want the output to be:
arr[0] = 1
arr[1] = 2
arr[2] = 3
我正在使用strtok()函数。 但是,下面的代码无法显示预期的结果:
int main()
{
char b[] = "1 2 3 4 5";
char *p = strtok(b," ");
int init_size = strlen(b);
int arr[init_size];
int i = 0;
while( p != NULL)
{
arr[i++] = p;
p = strtok(NULL," ");
}
for(i = 0; i < init_size; i++)
printf("%s\n", arr[i]);
return 0;
}
You have to convert string to int using
strtol
for example:When you print the value of array, use
%d
for integer value instead of%s
. You useinit_size
is wrong. Because in the string, it has some space character. Your printing part should change to: