【问题标题】:How to split a numeric string and then store it in an int array in c?如何拆分数字字符串,然后将其存储在 c 中的 int 数组中?
【发布时间】:2020-05-17 14:13:11
【问题描述】:

我想将一个数字字符串拆分为单独的数字,然后将每个数字存储在一个整数数组中。 例如,我们有这个数字字符串: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;
}

【问题讨论】:

    标签: c arrays string strtok


    【解决方案1】:

    您必须使用 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 是错误的。因为在字符串中,它有一些空格字符。您的打印部分应更改为:

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

    【讨论】:

    • 非常感谢您的回答,但是我收到警告说“赋值使指针从没有强制转换的整数”for ```arr[i++] = strtol(p,NULL,10);并且格式 '%d' 需要 int 类型的参数”并希望我在打印部分使用 %ls
    • 尝试使用arr[i++] = (int ) strtol(p, NULL, 10);
    • strtol 返回 long int 类型。您可以使用atoi(p) 代替strtol(它已被贬值),或者使用演员作为上面的评论。
    • @user47 尝试复制并粘贴我的代码,因为我没有看到任何警告。如果您仍然有警告,请使用其他解决方案作为上面的评论。
    • 非常感谢,不过,现在它只不间断地打印数字 1 :(
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-04
    • 1970-01-01
    • 1970-01-01
    • 2016-06-04
    • 2021-08-01
    • 1970-01-01
    相关资源
    最近更新 更多