how to pad zero in right hand side

This is a discussion on how to pad zero in right hand side within the C Programming forums, part of the General Programming Boards category; Hi all, I want to pad zero in right hand side, but I can't get the expected result, please help ...

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

    how to pad zero in right hand side

    Hi all, I want to pad zero in right hand side, but I can't get the expected result, please help , many thanks!!!

    123456781

    after padded zero in right hand side
    1234567810000000

    Code:
    char* s="123456781";
    
    int count=strlen(s);
    
    //fill zero, and the length of string is 8bytes, 16bytes, 24bytes....
    int remain=8-(count%8); 
    for( i=0; i< remain; i++)
    {
    strcat(s, "0");
    }
    
    printf("%s", s);

  2. #2
    Registered User camel-man's Avatar
    Join Date
    Jan 2011
    Location
    Under the moon
    Posts
    643
    You can not modify a string literal, try allocating space for your string first.

  3. #3
    Registered User
    Join Date
    Apr 2012
    Posts
    49
    Code:
    char* s="123456781";
    
    
    int count=strlen(s);
    
    //fill zero, and the length of string is 8bytes, 16bytes, 24bytes....
    int remain=8-(count%8); 
    
    char* output=(char*) malloc(count+remain+1);
    strncpy(output, s, count);
    
    int i=0;
    for(i=0; i<remain; i++)
    {
    strncpy(output, "0",1);
    }
    
    
    printf("%s", output);




    I have modified the code, is there any wrong?
    Last edited by homoon; 04-19-2012 at 12:00 AM.

  4. #4
    Registered User whiteflags's Avatar
    Join Date
    Apr 2006
    Location
    United States
    Posts
    7,758
    Yeah you don't know how these functions work. For starters, output is not properly terminated. All C strings end with '\0'.
    Code:
    strncpy(output, "0",1);
    This does not append any zeros, because you started in the wrong place. You also don't make any progress. This will just put a '0' character in the first character of output for as many times as you call it. You were much closer with your first attempt.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. function return on right hand side of "="
    By sed_y in forum C Programming
    Replies: 11
    Last Post: 08-27-2011, 11:28 PM
  2. Replies: 26
    Last Post: 03-08-2011, 05:23 PM
  3. placing two bmp images side by side
    By nina_code in forum C++ Programming
    Replies: 2
    Last Post: 07-14-2009, 12:10 PM
  4. what are some other 'life skills' that can go hand in hand with programming
    By Shadow12345 in forum A Brief History of Cprogramming.com
    Replies: 10
    Last Post: 01-17-2003, 02:34 PM
  5. Printing text side by side
    By PJYelton in forum C++ Programming
    Replies: 5
    Last Post: 10-14-2002, 12:46 PM

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