Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Padding specified number of zeros to a char array

Tags:

c++

I want to pad a given char array to make it a 15 character array.

For eg. if the array contains two characters 1, 2 then 13 0 characters should be padded to make in 000000000000012 and if contains five characters then 10 0s should be padded. The resultant array should contain 15 characters always.

Found one solution here but that’s for stl string I need similar solution for char arrays. Please help. What I have tried is below:

char moneyArray[256];
memset(moneyArray, 0, 256);    
for(int i=0;i<(15-strlen(moneyArray))-1;i++)
    sprintf(moneyArray,"0%s",moneyArray);

But I am looking for a standard solution if possible using a std function may be?


2 Answers

You can use the pad function below:

#include <iostream>
#include <cstring>

void pad(char *s, int n, int c) {
    char *p = s + n - strlen(s);
    strcpy(p, s);
    p--;
    while (p >= s) { p[0] = c; p--; }
}

int main () { 
    char b[16] = "123";
    pad(b, 15, '0');
    std::cout << b << std::endl;
    return 0; 
}
like image 160
perreal Avatar answered Oct 23 '25 05:10

perreal


If you're fine with std::string (and I think you should be), you can make use of its fill constructor:

char        s[]    = "12";
std::string padded = std::string( (15 - strlen(s) ), '0').append(s);

Of course you might want to check whether strlen(s) > 15 first.

like image 28
Biffen Avatar answered Oct 23 '25 04:10

Biffen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!