Thread: sprintf

  1. #1
    Registered User
    Join Date
    Jun 2011
    Posts
    3

    Talking sprintf

    Hello.

    I have two uint8_t values that i would like to combine in a char array. I know I can use sprintf to store one of them in a char array, like shown below. How do i append the other one?

    Thanks a lot for helping me out

    uint8_t adc_readingL = 174;
    uint8_t adc_readingH = 236;
    unsigned char adc_reading_chars[4];
    sprintf(adc_reading_chars, "%i", adc_readingL);

  2. #2
    Registered User
    Join Date
    Mar 2011
    Posts
    278
    sprintf works sort of like printf, just add more %i terms

  3. #3
    Registered User
    Join Date
    Jun 2011
    Posts
    3
    Thanks for the quick reply! so like this:? Also array length of 6 is sufficient, right? The values will never be above 255

    unsigned char adc_reading_chars[6];
    sprintf(adc_reading_chars, "%i", adc_readingL, "%i", adc_readingL);

  4. #4
    Registered User hk_mp5kpdw's Avatar
    Join Date
    Jan 2002
    Location
    Northern Virginia/Washington DC Metropolitan Area
    Posts
    3,817
    If both values are at most 3 digits long, then you will need a minimum of 7 characters for your array - 3+3+1 (for the null terminating character) - in order to be safe.
    Code:
    char adc_reading_chars[7];
    sprintf(adc_reading_chars, "%i%i", adc_readingL, adc_readingL);
    "Owners of dogs will have noticed that, if you provide them with food and water and shelter and affection, they will think you are god. Whereas owners of cats are compelled to realize that, if you provide them with food and water and shelter and affection, they draw the conclusion that they are gods."
    -Christopher Hitchens

  5. #5
    Registered User
    Join Date
    Jun 2011
    Posts
    3
    Thanks

  6. #6
    Registered User
    Join Date
    May 2009
    Posts
    4,183
    If your system supports "snprintf" it is safer that "sprintf".

    Tim S.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Replies: 5
    Last Post: 02-12-2010, 08:02 PM
  2. sprintf
    By rocketman03 in forum C Programming
    Replies: 3
    Last Post: 10-25-2008, 03:11 PM
  3. sprintf()
    By reza_45 in forum C Programming
    Replies: 7
    Last Post: 08-15-2008, 04:40 PM
  4. sprintf
    By bobthebullet990 in forum C Programming
    Replies: 7
    Last Post: 08-31-2007, 03:44 AM
  5. sprintf
    By krappykoder in forum C++ Programming
    Replies: 12
    Last Post: 11-18-2004, 05:45 PM