0

I have a rather newbie question but I can't figure it out.

Lets say I have this char array:

char array[] = "10,11,12,1,0,1,0";

How can I convert it to an array of int like this?

int arrayINT[] = {10,11,12,1,0,1,0};
  • Are you sure those arrays contain what you want them to? In the first case, are you looking for an array which contains the values 10, 11, 12, 1, 0, 1 and 0? (That's not what you have -- you have a string containing an ASCII 1, an ASCII 0, an ASCII comma, and so on.) And the second one I'm almost certain isn't what you want - it's an array of pointers to very short strings (if the compiler even allows it). – Mark Smith Mar 22 '16 at 11:36
  • yes i know, i'm building http server and this is a part of a string that i recieve from my web page – Houdasek Mar 22 '16 at 11:42
  • OK. Do you want it to end up as int arrayINT[] = { 10, 11, 12, 1, 0, 1, 0 } ? – Mark Smith Mar 22 '16 at 11:43
  • Yes, it seems that Majenko's answer below is working properly :) – Houdasek Mar 22 '16 at 11:51
  • I'll edit your question then, so it asks what you want. – Mark Smith Mar 22 '16 at 11:55
7

If you have a C string containing ASCII numbers with a common delimiter (comma in this case) you can use the strtok() function to split it into individual strings. Then you can use atoi() to convert those individual strings into integers:

char array[] = "10,11,12,1,0,1,0";
int intArray[7]; // or more if you want some extra room? 

int ipos = 0;
// Get the first token from the string
char *tok = strtok(array, ",");
// Keep going until we run out of tokens
while (tok) {
    // Don't overflow your target array
    if (ipos < 7) {
        // Convert to integer and store it
        intArray[ipos++] = atoi(tok);
    }
    // Get the next token from the string - note the use of NULL
    // instead of the string in this case - that tells it to carry
    // on from where it left off.
    tok = strtok(NULL, ",");
}

Note that strtok() is a destructive function. It will decimate your existing string with NULL characters as it slices it up.

  • Amazing, this is working. I knew about strtok() and atoi() but couldn't get them working properly. Thanks very much!! – Houdasek Mar 22 '16 at 11:49
  • A major improvement would be counting the commas in the string and allocating an array of the approriate size. On the other hand, why not convert the nth value at runtime? – ott-- Mar 22 '16 at 22:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.