Thread: convert character array to integer array in c

  1. #1
    Registered User
    Join Date
    Apr 2016
    Posts
    8

    convert character array to integer array in c

    I have a char array with the following:

    Code:
    char initCost[] = {"0", "-1", "0"};
    And I need to convert them to an integer array that should end up like this:

    Code:
    int initCost[] = {0, -1, 0};
    I have tried many different approaches that I found online but no luck yet. Any help will be greatly appreciated.

  2. #2
    Registered User
    Join Date
    May 2015
    Posts
    228
    One approach is to use the ASCII approach where you take the character itself and subtract it based on its value.

    '0' is 48 so 48 - 48 is 0.
    '1' is 49 so 49 - 48 is 1.

    You can also use atoi the function to convert each character to an integer but the problem with this is that it does not protect you against overflow and underflow.(Now that I recall I think atoi uses the ASCII approach as well)

    My personal recommendation is to strtol as it tells you if you got an overflow or underflow and helps you when you are doing validation. The only thing is that you are going to have truncate to an int because it converts a string to a long.
    Last edited by deathslice; 04-11-2016 at 12:38 PM.

  3. #3
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    693
    stdlib.h has a function called "atoi". This will take a string and return the int value.

    C library function - atoi()
    Code:
    int get_random_number(void)
    {
       return 4; //chosen by fair dice roll.
                 //guaranteed to be random
    }

  4. #4
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    If you want to convert strings to integers, look into functions like "strtol".

    However, this is not right:

    Code:
    char initCost[] = {"0", "-1", "0"};
    You are trying to initialize an array of char with strings. You could use characters (e.g. '0' instead of "0"), but this would make representing -1 more difficult. Perhaps you meant to use an array of char*.

  5. #5
    Registered User
    Join Date
    Apr 2016
    Posts
    8
    I see what you mean, but the situation here is that I am reading into my char buffer[256] data that looks like this:

    0, -1, 0, 1, 0, 1, 2, 1, 3, 3, 2, 7

    So I need to be able to convert that into individual integers and stotr them into a int array. I apologize for the confusion, I am brand new to these site.

  6. #6
    Registered User
    Join Date
    Apr 2016
    Posts
    8
    I see what you mean, but the situation here is that I am reading into my char buffer[256] data that looks like this:


    0, -1, 0, 1, 0, 1, 2, 1, 3, 3, 2, 7


    So I need to be able to convert that into individual integers and stotr them into a int array. I apologize for the confusion, I am brand new to these site.

  7. #7
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    Where are you reading this data from? Does the data conform to a specific format?

  8. #8
    Registered User
    Join Date
    Apr 2016
    Posts
    8
    Its coming from another pc, this is part of a client/server communication program.

    bzero(buffer, 256);
    n = read(clntsocket, buffer, 255);

  9. #9
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Well, I mean, char is just a smaller int:

    Code:
    int main(void)
    {
        size_t x = 0;
        char buffer[256] = {0, -1, 0, 1, 0, 1, 2, 1, 3, 3, 2, 7};
        int content[256] = { 0 };
    
        for (x = 0; x < 12; x++) {
            content[x] = (int) buffer[x];
            printf("content[%2zu] = %d\n", x, content[x]);
        }
        printf("...\n");
        return 0;
    }
    
    content[ 0] = 0
    content[ 1] = -1
    content[ 2] = 0
    content[ 3] = 1
    content[ 4] = 0
    content[ 5] = 1
    content[ 6] = 2
    content[ 7] = 1
    content[ 8] = 3
    content[ 9] = 3
    content[10] = 2
    content[11] = 7 
    ...
    The cast isn't even required.

  10. #10
    Registered User
    Join Date
    Apr 2016
    Posts
    8
    I had done that but I get this back:

    array[0] = 48
    array[1] = 44
    array[2] = 50
    array[3] = 44
    array[4] = 49
    array[5] = 44
    array[6] = 49
    array[7] = 44
    array[8] = 45
    array[9] = 49
    array[10] = 44
    array[11] = 48

  11. #11
    Lurking whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    9,612
    Okay, well, we could have gotten here faster than how we did. It's always good to post a short, simple, self-contained, correct example. Anytime you go onto a programming forum (not just these) it is helpful to post one to understand the problem, and find a solution, faster.

    The reason this was hard for you was because you have some commas and hyphens in the data you read.

    array[1] = 44 = ','
    ...
    array[8] = 45 = '-'
    ...

    You need a parsing strategy that can deal with this cruft. The good thing is we know the buffer is zero terminated. Note the call to bzero(), and reading a slightly smaller string in the code fragment you gave us, graciously, in post #8.

    That means you can do something similar to this:
    Code:
    #include <stdlib.h>
    
    char *p = buffer; 
    char *trail;
    size_t x = 0;
    while (*p != '\0')
    {
       array[x] = strtol(p, &trail, 10); 
       if (*trail == ',') 
       {
          p = trail + 1;
          ++x;
       }
       else if (*trail == '\n' || *trail == '\0') {
          break;
       }
       else {
          fprintf(stderr, "parsing error: expected ',' got: '%c'\n", *trail);
          break;
       }
    }
    The code does assume that array is large enough for all the data. If that could be untrue, then you would have to check x against array's size in order to avoid an out of bounds array write.
    Last edited by whiteflags; 04-11-2016 at 07:47 PM.

  12. #12
    Registered User
    Join Date
    Jun 2015
    Posts
    1,640
    You can also use sscanf.
    Code:
    #include <stdio.h>
    
    #define ASIZE 100
    
    int main() {
        char buf[] = "0, -1, 0, 1, 0, 1, 2, 1, 3, 3, 2, 7";
        int a[ASIZE];
        int d = 0, n = 0, sz = 0, i;
        char *b;
    
        for (b = buf; sscanf(b, "%d ,%n", &d, &n) == 1; b += n) {
            if (sz >= ASIZE) {
                fprintf(stderr, "Error: array overflow\n");
                break; // print them anyway
            }
            a[sz++] = d;
        }
    
        for (i = 0; i < sz; i++)
            printf("%2d: %2d\n", i, a[i]);
    
        return 0;
    }

  13. #13
    Registered User
    Join Date
    Jun 2011
    Posts
    4,513
    You have a comma-separated list of numbers (44 is the ASCII decimal value for comma).

    Some additional ideas, beyond what has been suggested:

    Look into using "strtok" to break up the string into separate number sub-strings, and convert each sub-string to its equivalent number.

    Use "strtol" directly, though you'd have to be careful with the pointers to take the commas into account:

    Code:
    #include <stdio.h>
    #include <stdlib.h>
    
    int main(void)
    {
        char str[] = "0,-1,0,1,0,1,2,1,3,3,2,7";
        char *p;
        int data[12];
        int i;
    
        data[0] = strtol(str, &p, 10);
    
        for(i = 1; i < 12; i++)
            data[i] = strtol(p+1, &p, 10);
    
        for(i = 0; i < 12; i++)
            printf("%d\n", data[i]);
    
        return 0;
    }
    Last edited by Matticus; 04-11-2016 at 08:00 PM.

  14. #14
    Registered User
    Join Date
    Apr 2016
    Posts
    8
    I want to thank you all for your great help, I was able to make it work!!!! Thank you again

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Converting character array into an integer array
    By Digisweep in forum C Programming
    Replies: 4
    Last Post: 12-06-2013, 07:03 PM
  2. Convert Integer to Hex in an array of chars
    By anasimtiaz in forum C Programming
    Replies: 12
    Last Post: 07-22-2009, 05:29 PM
  3. Converting character array to integer array
    By quiet_forever in forum C++ Programming
    Replies: 5
    Last Post: 04-02-2007, 05:48 AM
  4. Convert Integer into an array
    By ubernos in forum C Programming
    Replies: 2
    Last Post: 11-08-2005, 10:30 AM
  5. how do i convert a char array to an integer ? (c++)
    By mbh in forum C++ Programming
    Replies: 3
    Last Post: 10-31-2002, 04:49 AM