Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/c/56.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中将字符串数组转换为Int数组的最佳方法_C_Atoi_Strtol - Fatal编程技术网

在C中将字符串数组转换为Int数组的最佳方法

在C中将字符串数组转换为Int数组的最佳方法,c,atoi,strtol,C,Atoi,Strtol,我当前的问题是从stdin读取未知数量的整数。我的方法是使用gets将整行存储为char数组char str[50]。我试图解析char数组,并将每个字符串int转换为整数,然后存储在int数组中。我尝试使用strtol nums[I]=strtolA和&endptr,其中A是字符数组。然而,当A的其余部分也是数字时,endptr似乎并没有存储任何内容。例如,如果A是8 hello endptr=hello,但当A是8 6 4 endptr时,则该值为零 有更好的方法吗?这对atoi有可能吗?非

我当前的问题是从stdin读取未知数量的整数。我的方法是使用gets将整行存储为char数组char str[50]。我试图解析char数组,并将每个字符串int转换为整数,然后存储在int数组中。我尝试使用strtol nums[I]=strtolA和&endptr,其中A是字符数组。然而,当A的其余部分也是数字时,endptr似乎并没有存储任何内容。例如,如果A是8 hello endptr=hello,但当A是8 6 4 endptr时,则该值为零

有更好的方法吗?这对atoi有可能吗?非常感谢您的帮助!谢谢

char A[1000];
long nums[1000];
printf("Enter integers: ");
gets(A);
char *endptr;
int i=0;
while(endptr!=A){
    nums[i]=strtol(A, &endptr, 10);
    i++;
}

这将提取正整数,并跳过任何非整数的内容:

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

char string[1024];
long numbers[512]; // worst case ~ 1/2 number of chars = "1 1 1 1 1 1 ... 1"

/* ... */

printf("Enter integers: ");
fgets(string, sizeof(string), stdin);

char *endptr, *ptr = string
int count = 0;

while (*ptr != '\0') {
    if (isdigit(*ptr)) {
        numbers[count++] = strtol(ptr, &endptr, 10);
    } else {
        endptr = ptr + 1;
    }

    ptr = endptr;
}

迭代数组并转换每个数字。有什么问题吗?显示您的代码。这不是编码服务。没有编码的模糊问题。你能发布一些代码吗?如果A=12 35 78,我将如何迭代字符数组?我可以将其转换为123578,但这不是我需要的。我添加了一些原始代码。如果有无效输入,1停止。2跳过?e、 g.输入:12 hello 34,获取{12}或{12,34}