在C中,如何将字符串包含数字转换为int数组?

时间:2017-01-08 22:48:58

标签: c arrays string

在我的C程序中,我收到如下输入: 1,2,5,13,​​18 如何将此字符串转换为实际数字? 我试过了strtok(),但它给了我分段错误,我不明白为什么,也许你可以帮我解决这个问题?

1 个答案:

答案 0 :(得分:1)

您尚未在此处提供代码,可能是您没有以正确的方式使用strtok()。请参阅文档并查看该页面中的示例,以了解有关strtok()的使用的更多信息。

使用strtok()对字符串进行标记,然后使用atoi()将字符串转换为数字。

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

int main()
{
    char str[] = "1,2,5,13,18";
    char* pch;
    pch = strtok(str, ",");
    while(pch)
    {
        int x = atoi(pch);
        pch = strtok(NULL, ",");
        printf("%d\n", x);
    }

    return 0;
}
相关问题