将数组字符串转换为C语言数组的最佳方法

时间:2016-09-13 20:24:52

标签: c atoi strtol

我目前的问题是从stdin读取未知数量的整数。我的方法是使用gets()将整行存储为char数组(char str[50])。我试图解析char数组并将每个“string int”转换为整数并存储在int数组中。我尝试使用strtol(nums[i]=strtol(A, &endptr, 10),其中A是char数组。但是,当A的其余部分也是数字时,endptr似乎不存储任何内容。例如,如果A是“8 hello”endptr =你好,但是当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++;
}

1 个答案:

答案 0 :(得分:0)

这应该提取(正)整数并跳过任何不是整数的其他东西:

#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;
}
相关问题