Thread: Copying an INT into a Char array?

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    145

    Copying an INT into a Char array?

    Say I have a char array equal to "ahello"

    (ie array[0] = 'a' && array[1] = 'h' ect ect)

    Now i need to replace the letter a (array[0]) with a number from 1-15, so obviously if the number is bigger than 9, then the "hello" part needs to be shifted along

    What is a good way of doing this?
    Last edited by Wiretron; 08-26-2006 at 03:47 PM.

  2. #2
    System Novice siavoshkc's Avatar
    Join Date
    Jan 2006
    Location
    Tehran
    Posts
    1,246
    First of all there can be a better solution for your problem. Why making "ahello" and than replacing a?

    Second for your question. Shift it.
    Code:
    int len = strlen(carray);
    
    for( int i = len; i >= 0 ; --i)
    {
           carray[i + 1] = carray[i];
    }
    carray[++len] = '\0';
    Just remember that carray should be carray[7], [edit:] one more than "ahello".
    Learn C++ (C++ Books, C Books, FAQ, Forum Search)
    Code painter latest version on sourceforge DOWNLOAD NOW!
    Download FSB Data Integrity Tester.
    Siavosh K C

  3. #3
    Gawking at stupidity
    Join Date
    Jul 2004
    Location
    Oregon, USA
    Posts
    3,218
    You could also use memmove():
    Code:
    memmove(array + 2, array + 1, 6);
    If you understand what you're doing, you're not learning anything.

  4. #4
    Registered User
    Join Date
    Oct 2001
    Posts
    2,934
    Code:
    char temp[30];
    sprintf(temp, "%d%s", num, array);
    strcpy(array, temp);

  5. #5
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > so obviously if the number is bigger than 9, then the "hello" part needs to be shifted along
    And then what - you've got "15ello"
    Are you going to do something with 'e' then 'l' as well?

    Basically, are you encoding the whole string in numeric form?
    If you are, you're best constructing the new string in another buffer rather than shuffling everything along one char at a time.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. how to combine these working parts??
    By transgalactic2 in forum C Programming
    Replies: 0
    Last Post: 02-01-2009, 08:19 AM
  2. Replies: 26
    Last Post: 11-30-2007, 03:51 AM
  3. Replies: 3
    Last Post: 05-13-2007, 08:55 AM
  4. Converted from Dev-C++ 4 to Dev-C++ 5
    By Wraithan in forum C++ Programming
    Replies: 8
    Last Post: 12-03-2005, 07:45 AM
  5. My graphics library
    By stupid_mutt in forum C Programming
    Replies: 3
    Last Post: 11-26-2001, 06:05 PM