Get element size of a vector? [duplicate]

2

I have a vector like this: int nums[10] + {1235, 14627, 1625161, 54437};

Always the element will be greater than or equal to 1000, that is, with a length equal to 4, and can be extended up to 10 digits. I want to know how I get the length of these integers from my vector. That is, using the example vector, I have the first element that has 4, others with 5, 7 and 5 respectively. But how do I get the length by the code?

    
asked by anonymous 08.10.2015 / 05:36

1 answer

4

So suddenly I see two ways: by converting to string or by using the function log() .

#include <string.h> // para strlen()

int nums[] = {1235, 14627, 1625161, 54437};
for (int k = 0; k < sizeof nums / sizeof *nums; k++) {
    char tmp[12];
    sprintf(tmp, "%d", nums[k]);
    printf("O numero %d tem comprimento %d.\n", nums[k], (int)strlen(tmp));
}

or

#include <math.h> // para log()

int nums[] = {1235, 14627, 1625161, 54437};
for (int k = 0; k < sizeof nums / sizeof *nums; k++) {
    printf("O numero %d tem comprimento %d.\n", nums[k], (int)log10(nums[k]) + 1);
}
    
08.10.2015 / 10:37