Unable to assign int to string. HELP!

This is a discussion on Unable to assign int to string. HELP! within the C Programming forums, part of the General Programming Boards category; Code: #include <stdlib.h> #include <stdio.h> int main(void) { char newString[] = "00000"; int a = 0; a = 8; newString[1] ...

  1. #1
    Registered User
    Join Date
    Apr 2012
    Posts
    18

    Unable to assign int to string. HELP!

    Code:
    #include <stdlib.h>
    #include <stdio.h>
    
    int main(void)
    {
       char newString[] = "00000";
       int a = 0;
    
       a = 8;
       newString[1] = a;
    
       printf("%s", newString);
    
       return EXIT_SUCCESS;
    }
    result:
    00000

    how can i assign 8 to newString[1] and make the end result as:
    08000?

  2. #2
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,588
    For single digits, you can do this
    newString[1] = a + '0';

    For anything more complicated, then sprintf() is probably a good bet.
    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.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Unable to assign to a variable
    By suryak in forum C Programming
    Replies: 2
    Last Post: 11-16-2011, 10:43 AM
  2. Unable to compare string with 'getter' returned string.
    By Swerve in forum C++ Programming
    Replies: 2
    Last Post: 10-30-2009, 05:56 PM
  3. assign value to string
    By rahulsk1947 in forum C Programming
    Replies: 3
    Last Post: 04-06-2006, 03:40 AM
  4. Replies: 12
    Last Post: 10-14-2003, 10:17 AM
  5. Replies: 10
    Last Post: 03-19-2003, 01:15 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21