c - strtoull在C中正确使用

标签 c arrays char strtoull

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

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

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

所以现在我需要将它转换为一个 unsigned long long 数组。 我知道我可以使用 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 语言中可以这样做吗?

最佳答案

strtoull 的第二个参数是指向 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

关于c - strtoull在C中正确使用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40753285/

相关文章:

c - 在c中调用free时发生双重释放或损坏错误

c - 对不同数据类型的操作

python - 快速随机配对排列

C while(false) 循环

c - 多个线程写入同一个文件

arrays - 循环声音 ActionScript Flash

javascript - 更改对象内的数组(反之亦然)会更改更改前后对该数组的所有引用

c - 获取整数的负号并将其存储为 char 的最佳方法是什么?

java - 如何使用具有字符输入和 boolean 输出的方法?

c - 将 float 32 精确转换为 unsigned Short 或 unsigned char