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

How to split a numeric string and then store it in an int array in c?

我想将一个数字字符串拆分成单独的数字,然后将每个数字存储在一个整数数组中。 例如,我们有这个数字字符串:1 2 3,我希望输出为:

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;
}

您必须使用 strtol 将字符串转换为 int,例如:

   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," ");
    }

打印数组的值时,使用 %d 作为整数值而不是 %s。你用init_size是错误的。因为在字符串中,它有一些 space 字符。您的打印部分应更改为:

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

完整代码:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>

int main()
{
    char b[] = "1 2 3 4 5";
    int init_size = strlen(b);
    int arr[init_size];
    int i = 0;

    char *p = strtok(b," ");
    while( p != NULL)
    {
       arr[i++] = strtol(p, NULL, 10);
       p = strtok(NULL," ");
    }

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

return 0;
}