0

だから私はこのような文字列を持っています:

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

これは一例です。配列にはさらに多くの数字が含まれる可能性がありますが、必ず ] で終わります。

したがって、これを unsigned long long の配列に変換する必要があります。strtoull() を使用できることはわかっていますが、3 つの引数が必要で、その 2 番目の引数の使用方法がわかりません。また、配列を適切な長さにする方法を知りたいです。コードを次のようにしたいと思いますが、疑似コードではなく 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

の 2 番目の引数strtoullchar *、文字列引数の数字の後の最初の文字へのポインターを受け取る へのポインターです。3 番目の引数は、変換に使用するベースです。ベース 0 では、C 整数リテラルと同様に、プレフィックスで0x16 進数変換を指定し、プレフィックスで 8 進数を指定できます。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
于 2016-11-22T23:13:53.030 に答える