TonyB
01-27-2003, 05:29 PM
Hello,
I am learning C and have a problem. I am trying to center a string in a char array, below is the code:
char
*center_str(int wid, char *instr, char *outstr)
{
int nspaces; /* number of spaces to be filled */
nspaces = (wid - strlen(instr))/2;
if(nspaces<0) nspaces = 0;
strcpy(outstr, "");
while(nspaces--) strcat(outstr, " ");
strcat(outstr, instr);
return(outstr);
}
I call it like this:
char instr[80];
char outstr[80];
sprintf(instr,"%s", "this is a test");
center_str(80,instr, outstr);
printf("%s",outstr);
The "instr" should be centered in "outstr", but both char arrays hold the same string in the same location in the string, in short, instr is not centered in outstr. Is there a problem with my center_str routine?
sprintf should add a terminating NULL to the end of the string I put into instr. The code : nspaces = (wid - strlen(instr))/2; should find the length of the string (14) and subtract it from 80 (66) then div by 2 (33). This should be the starting location for the string in outstr after padding it with spaces, is this correct?
TIA
I am learning C and have a problem. I am trying to center a string in a char array, below is the code:
char
*center_str(int wid, char *instr, char *outstr)
{
int nspaces; /* number of spaces to be filled */
nspaces = (wid - strlen(instr))/2;
if(nspaces<0) nspaces = 0;
strcpy(outstr, "");
while(nspaces--) strcat(outstr, " ");
strcat(outstr, instr);
return(outstr);
}
I call it like this:
char instr[80];
char outstr[80];
sprintf(instr,"%s", "this is a test");
center_str(80,instr, outstr);
printf("%s",outstr);
The "instr" should be centered in "outstr", but both char arrays hold the same string in the same location in the string, in short, instr is not centered in outstr. Is there a problem with my center_str routine?
sprintf should add a terminating NULL to the end of the string I put into instr. The code : nspaces = (wid - strlen(instr))/2; should find the length of the string (14) and subtract it from 80 (66) then div by 2 (33). This should be the starting location for the string in outstr after padding it with spaces, is this correct?
TIA