Home > Enterprise >  Convert String into integer array in C
Convert String into integer array in C

Time:07-13

I want to convert a string or char array into an integer array. The string is in this format

example:

char *temp
1 2
3 4 
9 7

that should be converted into

int arr[] = {1,2,3,4,9,7}

Is there a string funtion that does this for you?

CodePudding user response:

Was not sure what you are specifically looking for, below is a function you can pass input of form

1 2
3 4
5 6
...
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

int * str_to_int(char *lines) {
    int *int_arr;
    int i, offset, index;
    // alloc mem for int arr
    int_arr = malloc(sizeof(int) * (strlen(lines) / 2));
    index = 0;
    // using sscanf() "convert" string to int
    while(sscanf(lines, "%d%n", &i, &offset) == 1) {
        // offset increments ptr to lines
        lines  = offset;
        int_arr[index  ] = i;
    }
    return int_arr;
}

CodePudding user response:

Here is an example of how to convert from a string array to a int array,

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int* convert(char* c)
{
    int len=strlen(c),i;
    int *a=(int*)malloc(len*sizeof(int));
    for(i=0;i<len;i  )
        a[i]=c[i]-48;
    return a;
}
int main(int argc, char const *argv[])
{
    char c[100];
    scanf("%s",c);
    int *a=convert(c);
    free(a);
    return 0;
}
  • Related