Thread: How can you take a string of numbers and turn it into an array of integers?

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

    How can you take a string of numbers and turn it into an array of integers?

    I know strings are essentially just arrays of characters, so what would be the easiest way to take each individual digit and put it into a separate space in an array?

    ex.) *str = "90210"

    array[0] = 9
    array[1] = 0
    array[2] = 2
    array[3] = 1
    array[4] = 0

    all my attempts at achieving this just result in an array full of garbage numbers

    what ive done is:

    Code:
    int *array;
    array = malloc(sizeof(int)*(strlen(str));
    
    for(i=0; i<strlen(str); i++)
    {
    array[i] = str[i]
    }
    any help with this would be greatly appreciated.

    also, I should mention that the string will be defined in main, and its converted into an array in a separate function.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Hint: subtract '0' from each character, assuming (or having checked) that it is in the range of '0' to '9'.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Oct 2013
    Posts
    29
    that worked, thank you!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 2
    Last Post: 03-02-2014, 09:41 AM
  2. Replies: 12
    Last Post: 02-28-2008, 06:19 PM
  3. Turn a string into an array
    By The Letter J in forum C++ Programming
    Replies: 8
    Last Post: 12-22-2004, 12:08 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