I wrote this function that’s supposed to do StringPadRight("Hello", 10, "0") -> "Hello00000".
char *StringPadRight(char *string, int padded_len, char *pad) { int len = (int) strlen(string); if (len >= padded_len) { return string; } int i; for (i = 0; i < padded_len - len; i++) { strcat(string, pad); } return string; }
It works but has some weird side effects… some of the other variables get changed. How can I fix this?
It might be helpful to know that
printfdoes padding for you, using%-10sas the format string will pad the input right in a field 10 characters long:Will output:
In this case:
-symbol means "Left align"10means "Ten characters in field"smeans you are aligning a string.printfstyle formatting is available in many languages and has plenty of references on the web. Here is one of many pages explaining the formatting flags. As usual WikiPedia’sprintfpage is of help too (mostly a history lesson of how widelyprintfhas spread).