如何拆分数字字符串,然后将其存储在c中的int数组中?

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:

       char *p = strtok(b," ");
        while( p != NULL)
        {
           arr[i++] = strtol(p, NULL, 10); // arr[i++] = p is wrong, because p is a string not an integer value
           p = strtok(NULL," ");
        }
    

    When you print the value of array, use %d for integer value instead of %s. You use init_size is wrong. Because in the string, it has some space character. Your printing part should change to:

        for(int j = 0; j < i; j++)
            printf("%d\n", arr[j]);