Hi everyone,
I am working on a function that pads atring from the back,
it works well but it doesn't produce the right result. that means
I designed the function so that when given a string like "Hello" which is 5 character long, the program should produce "Helloxxx" which should be 8 character long. I am somehow getting wrong something ? can anyone help me figure out why itdoes so ?
Code:
code
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
#include <stdio.h>
char *padstr(char *s, char c, int field, int pos);
int main( )
{
char str[] = "Hello" ;
//char c = 'x';
printf("the paded string is %s\n", padstr(str, 'x', 7, 1));
}
/* field = length of resulting string
* pos = 1 - left padded-- means desierd result is "Helloxxx "
* s = string to be formatted
* c = padding character
*/
char *padstr(char *s, char c, int field, int pos)
{
int i;
char tmpstr[9] = " ";
/* we won't accept wrong entry */
if (strlen(s) > field)
{
return 0;
}
/* clear the variable content first */
strcpy(tmpstr,"\0");
/* we want it right-padded */
if (pos == 1)
{
for (i =0; i < (field - strlen(s)); i++)
{ /* start padding the string at the back */
strcat(tmpstr, &c);
}
strcat(s,tmpstr);
}
return s;
}