簡體   English   中英

strtoull在C中正確使用

[英]strtoull use properly in C

所以我有一個像這樣的字符串:

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語言可以做到這一點嗎?

strtoull的第二個參數是一個指向char *的指針,該char *將接收一個指向字符串參數中數字之后的第一個字符的指針。 第三個參數是用於轉換的基礎。 像C整數文字一樣,基數0允許0x前綴指定十六進制轉換和0前綴指定八進制。

您可以通過以下方式解析行:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM