Thread: Assign value of multiple char array elements to int

  1. #1
    Registered User
    Join Date
    Jan 2006
    Posts
    62

    Assign value of multiple char array elements to int

    Code:
    int x
    char text[10] = {"123456789"};
    how do I assign the values in array elements text[3] and text[4] to int so int will equal 45?

  2. #2
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Code:
    /* silly way, converting each element to an integer */
    x = (text[3]-'0') * 10 + (text[4]-'0');
    
    /* slightly less silly way */
    char new[16] = { 0 };
    strncpy(new, text + 3, 2); /* copy text[3] and text[4] to new */
    new[2] = '\0'; /* null terminate new */
    x = atoi(new); /* or use strtol for error checking */

  3. #3
    Registered User
    Join Date
    Aug 2005
    Posts
    1,267
    Another simple way. Not very efficient when you want to do several characters.
    Code:
    int x
    char text[10] = {"123456789"};
    x = text[3] - '0' + text[4] - '0';

  4. #4
    Registered Luser cwr's Avatar
    Join Date
    Jul 2005
    Location
    Sydney, Australia
    Posts
    869
    Ancient Dragon, that's the way I suggested above, except I multiplied the first term by 10. Your way just adds them, producing 9, not 45.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 8
    Last Post: 03-10-2008, 11:57 AM
  2. get keyboard and mouse events
    By ratte in forum Linux Programming
    Replies: 10
    Last Post: 11-17-2007, 05:42 PM
  3. Personal Program that is making me go wtf?
    By Submeg in forum C Programming
    Replies: 20
    Last Post: 06-27-2006, 12:13 AM
  4. How do i un-SHA1 hash something..
    By willc0de4food in forum C Programming
    Replies: 4
    Last Post: 09-14-2005, 05:59 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