Thread: Turning a string of numbers into an array of individual integers

  1. #1
    Registered User
    Join Date
    Oct 2013
    Posts
    29

    Turning a string of numbers into an array of individual integers

    I know there is a clear solution to this, but I cant seem to find it.
    In my program, I am fed a string that contains integers such as
    Code:
    *str = "45678"
    and my program is simply supposed to read the number in and store each given number in a separate spot in an integer array. So basically, when my program has finished running it should be stored like:
    Code:
    arr[0] = 4
    arr[1] = 5
    arr[2] = 6
    arr[3] = 7
    arr[4] = 8
    the way I have been attempting to do this was just copying it to the array like so:
    Code:
    arr = malloc(sizeof(int) *(strlen(str));
    
    for (i=0; i<strlen(str); i++)
    {
    a->digits[i] = str[i];
    }
    however, this just seems to return an impossibly high garbage value when I do. I'm assuming the way I'm trying to store it is 'illegal', but I cant seem to find online a proper way to do it.

  2. #2
    Registered User
    Join Date
    Feb 2014
    Posts
    11
    Is the string a predefined string? As in its always going to be the same, or is it something the user inputs and can be changed?

  3. #3
    Registered User
    Join Date
    Oct 2013
    Posts
    29
    It is a predefined string given in the program's main function

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. replacing individual chars in a string array
    By Trekker182 in forum C Programming
    Replies: 7
    Last Post: 11-16-2013, 07:31 PM
  2. How do I read individual numbers from an input??
    By shockem in forum C Programming
    Replies: 12
    Last Post: 09-04-2012, 02:52 AM
  3. Replies: 12
    Last Post: 02-28-2008, 06:19 PM
  4. Replies: 4
    Last Post: 03-03-2003, 03:52 PM
  5. Extract numbers as integers from a string array
    By DarthC in forum C++ Programming
    Replies: 2
    Last Post: 03-23-2002, 05:09 PM