0

所以我有一个这样的字符串:

char numbers[] = "123,125,10000000,22222222222]"

这是一个例子,数组中可以有更多的数字,但它肯定会以 ] 结尾。

所以现在我需要将它转换为一个无符号长整数数组。我知道我可以使用 strtoull() 但它需要 3 个参数,我不知道如何使用第二个参数。另外我想知道如何使我的数组具有正确的长度。我想让我的代码看起来像这样,但不是伪代码,而是 C:

char numbers[] // string of numbers seperated by , and at the end ]
unsigned long long arr[length] // get the correct length
for(int i = 0; i < length; i++){
    arr[i]=strtoull(numbers,???,10)// pass correct arguments
}

在 C 中可以这样做吗?

4

1 回答 1

2

to 的第二个参数strtoull是指向 a 的指针char *,它将接收指向字符串参数中数字之后的第一个字符的指针。第三个参数是用于转换的基础。Base 0 允许0x前缀来指定十六进制转换和0前缀来指定八进制,就像 C 整数文字一样。

你可以这样解析你的行:

extern char numbers[]; // string of numbers separated by , and at the end ]
unsigned long long arr[length] // get the correct length
char *p = numbers;
int i;
for (i = 0; i < length; i++) {
    char *endp;
    if (*p == ']') {
        /* end of the list */
        break;
    }
    errno = 0;  // clear errno
    arr[i] = strtoull(p, &endp, 10);
    if (endp == p) {
        /* number cannot be converted.
           return value was zero
           you might want to report this error
        */
        break;
    }
    if (errno != 0) {
        /* overflow detected during conversion.
           value was limited to ULLONG_MAX.
           you could report this as well.
         */
         break;
    }
    if (*p == ',') {
        /* skip the delimiter */
        p++;
    }
}
// i is the count of numbers that were successfully parsed,
//   which can be less than len
于 2016-11-22T23:13:53.030 回答