Convert char array to int array?

I start in C. I have a char array in this format, for example, "12 23 45 9". How to convert it to an int {12,23,45,9} array? Thanks in advance.

+4
source share
5 answers

Use sscanf or strtol in a loop.

+5
source

The traditional but obsolete way to do this would be to use strtok() . Modern replacement for strsep() . Here is an example, right from the strsep() man page:

 char **ap, *argv[10], *inputstring; for (ap = argv; (*ap = strsep(&inputstring, " \t")) != NULL;) if (**ap != '\0') if (++ap >= &argv[10]) break; 

This breaks the input string into pieces using the provided delimiters (space, tab) and iterates over the pieces. You should be able to modify the above to convert each part to int using atoi() . The main problem with strsep() is that it modifies the input string and therefore is not thread safe.

If you know that the input string will always contain the same number of ints, another approach would be to use sscanf() to read all ints at a time:

 char *input = "12 23 45 9"; int output[5]; sscanf(inputstring, "%d %d %d %d %d", &output[0], &output[1], &output[2], &output[3], &output[4]); 
+1
source

You will need stdlib.h

 //get n,maxDigits char** p = malloc(sizeof(char*) * n); int i; for(i=0;i<n;i++) p[i] = malloc(sizeof(char) * maxDigits); //copy your {12,23,45,9} into the string array p, or do your own manipulation to compute string array p. int* a = malloc(sizeof(int) * n); int i; for(i=0;i<n;i++) a[i] = atoi(p[i]); 
0
source

You can calculate individual numbers using the following technique (but it does not convert them to the whole number):

Note. I use the int iteration loop to make it readable. Usually you just increment the char pointer:

 void PrintInts(const char Arr[]) { int Iter = 0; while(Arr[Iter]) { if( (Arr[Iter] >= '0') && (Arr[Iter]) <= '9') { printf("Arr[%d] is: %d",Iter, (Arr[Iter]-'0') ); } } return; } 

The above converts the ASCII number back to int, subtracting the smallest ASCII representation of set 0-9. So, if, for example, β€œ0” was represented by 40 (this is not so), and β€œ1” was represented by 41 (this is not so), 41-40 = 1.

To get the results you want, you want to use strtok and atoi:

 //Assumes Numbers has enough space allocated for this int PrintInts(const int Numbers[] const char Arr[]) { char *C_Ptr = strtok(Arr," "); int Iter = 0; while(C_Ptr != NULL) { Numbers[Iter] = atoi(C_Ptr); Iter++; C_Ptr = strtok(NULL," "); } return (Iter-1); //Returns how many numbers were input } 
0
source

What about:

 const char *string = "12 23 45 9"; int i, numbers[MAX_NUMBERS]; //or allocated dynamically char *end, *str = string; for(i=0; *str && i<MAX_NUMBERS; ++i) { numbers[i] = strtol(str, &end, 10); str = end; }; 

Although it is possible that you will get the final 0 in your array of numbers if the line has a space after the last number.

-1
source

All Articles