Transform a char vector into a vector of int in C

Asked

Viewed 1,403 times

0

char ch[] = {'7', '3', '0', '8'};
int [] nums[2];

void transformInt(char [] c1) {
    int n1[2];
    int j = 0;
    for (j = 0; j < 10; j++ ) {
        if (c1[j] != '0') {
            n1[j] = c1[j];
        } else break;    
        return n1;    
    }
}

Guys, I need to turn a char vector into an int vector, but I can’t. In this case, 0 would separate the two values. Thus, n1[0] would need to be equal to 73 and n1[1] equal to 8. I tried to create a method, but it does not even work to allocate the first value, I do not know what is wrong. Nor do I know how to return a vector method.

  • What is this array also? It would not be the case that you build a new array until you find a character '0' and then use the strtol function of <stdlib. h> to convert the string to an integer?

  • In this case, my difficulty is to build the new array until I find zero.

  • The array tam was wrong, it was to be C1

  • 1

    your code has syntax errors, nor compiles...take out at least the syntax errors and try to run the program

  • I edited the question by placing spaces...use spaces to separate operators (+, =, -, etc) and keys ({}), otherwise it becomes very difficult to understand when everything is stuck together

  • int [] nums[2]; this is not valid C

Show 1 more comment

2 answers

1

You can use the sscanf is a user-friendly method and present in stdio.h.

char myarray[5] = {'-', '1', '2', '3', '\0'};
int i;
sscanf(myarray, "%d", &i);

There are also other options like atoi and the strtol.

References: link 1 link 2

0

To pass an array as a function parameter, you would have to use pointer, and because of the complexity of the program, I believe this is not the case.
Instead of using some external function, I would subtract the character by - '0'.
When using '0' in your code, a conversion is made to the representative value of the ASCII table.
EX: '7' - '0' //According to ASCII table would equal 55 - 48
And the result 55-48 = 7
As an example

int main()
{   
    char ch[] = {'7', '3', '0', '8'};
    int nums[]={0,0}, i = 0;

    for (i = 0; i<4;i++){
        nums[i/2]= (nums[i/2]* 10) + (ch[i]-'0');
        //printf("nums[%i]= %i\n",(i/2),nums[i/2]); descomente para ver como a variavel é preenchida
    }
    printf("nums[0]= %i\n nums[1]= %i\n",nums[0],nums[1]);
    return 0;
}

This is a very useful tactic, especially for programs that will be sent to the URI

Browser other questions tagged

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