How to convert an integer vector to an integer-only variable?

Asked

Viewed 1,056 times

-1

I need to convert an integer vector to a single variable, example:

int teste[] = {2, 3, 5, 6};

for

int result = 2356;

how to do this? NOTE: I don’t have the vector size (+ - dynamic)

3 answers

2


discovered, functions as simple mathematics, where the last position of the vector is the unit, the penultimate to ten and so on, as in the above case:

teste[4] = teste[4]*1;
teste[3] = teste[3]*10;
teste[2] = teste[2]*100;

so, just create a looping that updates these values for us:

int numero = 0
for ( int i = 0; i < 4; i++){
         numero += teste[3-i] * powf(10, i);
    }

1

Take the size of the array and divide it by the size of an element to determine the amount of array elements.

#include <stdio.h>
int main() {
    int teste[] = {2, 3, 5, 6};
    int i, num=0, tam;
    tam = (sizeof teste)/sizeof(int);
    for (i=0; i< tam; i++)
        num = num * 10 + teste[i];
    printf("\nNúmero: %d\n", num);
    return 0;
}

0

An alternative would be to turn this vector into a "string" and then pass it in one piece:

char retorno_vetor[tam];
int retorno;

int teste[] = {2, 3, 5, 6};
int tam = sizeof(vetor)/sizeof(int);

for (i=0 ; i<tam ; i++)
    retorno_vetor[i] = itoa(teste[i]);
retorno = atoi(retorno_vetor);
  • 1

    Yes, I agree, but I avoided using this method because after some research, I was informed that the itoa and atoi functions are a little problematic, so I did not want to use them

Browser other questions tagged

You are not signed in. Login or sign up in order to post.