Thread: Unable to assign int to string. HELP!

  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 int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,660
    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.

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, 11: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, 02:15 PM