gpt4 book ai didi

c - 获取以逗号分隔的数字

转载 作者:行者123 更新时间:2023-12-01 23:14:57 25 4
gpt4 key购买 nike

我得到了以下字符串:

"312 ,22 ,+12 , -12 , 5331"

数字之间可以有超过 1 个空格。

我需要将它转换成这样的数组:

int arr[] = {312,22,-12,12,5331};

有没有一种使用 C89 的漂亮而优雅的方法来做到这一点?

最佳答案

使用strtok + atoi :

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

int main(int argc, char const *argv[])
{
char numbers_str[] = "312 ,22 ,+12 ,-12 ,5331", *currnum;
int numbers[5], i = 0;

while ((currnum = strtok(i ? NULL : numbers_str, " ,")) != NULL)
numbers[i++] = atoi(currnum);

printf("%d\n", numbers[3]);
return 0;
}

关于c - 获取以逗号分隔的数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9444476/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com