Thread: copy contents of array to single value?

  1. #1
    Registered User
    Join Date
    Oct 2005
    Posts
    24

    copy contents of array to single value?

    I have an array, lets call it buffer.

    buffer[0] = 9
    buffer[1] = 2
    buffer[2] = 3

    how would i get a variable, x, to equal 923 (not only those numbers, but the contents of the buffer, whatever they may be)

  2. #2
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Well you could start from the back of the array and as you go backwards through it summing, just create a multiple that gets 10 times bigger everytime you decrement the index.

    Code:
    int x;
    int sum = 0;
    int multiple = 1;
    for (x = 2; x > 0; x--) {
       sum += buffer[x] * multiple;
       mutiple *= 10;
       }
    Another way would be to use the itoa() function on each one and strcat() the values together and atoi() that value.

    Either way, I'm sure there is a better way. I wouldn't be suprised if one of the wiseasses in here came in with a STL function that does just what you're asking.
    Last edited by SlyMaelstrom; 12-02-2005 at 07:32 PM.
    Sent from my iPadŽ

  3. #3
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,401
    Quote Originally Posted by SlyMaelstrom
    I wouldn't be suprised if one of the wiseasses in here came in with a STL function that does just what you're asking.
    I would be. STL and C don't mix.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  4. #4
    Registered User
    Join Date
    Oct 2005
    Posts
    24
    i went with the atoi...thanks for the help

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 1
    Last Post: 12-10-2008, 11:29 AM
  2. question about multidimensional arrays
    By richdb in forum C Programming
    Replies: 22
    Last Post: 02-26-2006, 09:51 AM
  3. Replies: 1
    Last Post: 07-24-2002, 06:33 AM
  4. Help with an Array
    By omalleys in forum C Programming
    Replies: 1
    Last Post: 07-01-2002, 08:31 AM
  5. Hi, could someone help me with arrays?
    By goodn in forum C Programming
    Replies: 20
    Last Post: 10-18-2001, 09:48 AM