Re: Problem with strlen and string containing color codes

From: Peter Ajamian (pajamian@cheapsam.com)
Date: 08/27/99


Chuck Carson wrote:

> I am tring to print a string such in the following manner:
>
> sprintf(buf, "%-50s %d\r\n", string, var);
>
> However, if the string contains color codes, the second
> argument does not line up correctly, ie. sprintf does not
> display 50 spaces before the second var is printed.
>
> How can I force this to keep the spacing correct?

I just recently tackled the same exact problem and wrote a fairly simple
function which truncates or expands a string containing color codes to a
specific length.  all my color codes start with an & followed by a
single character specifying the specific code, the code for an actual &
is &&.  If your codes are different then change the function
accordingly...

/* The following function returns a string which will display length
characters
   from color_string taking into account color codes which may be
embedded in
   color_string.  It's purpose is to help make collumns line up when
some of
   the data may have color codes. Note:  return_buf must be large enough
to
   hold strlen(color_string) + length characters. */

char * color_truncate(const char * color_string, size_t length,
                      char * return_buf)
{
  char * bufptr;

  strcpy(return_buf, color_string);

  for (bufptr = return_buf; length && *bufptr; bufptr++) {
    if (*bufptr == '&') {
      bufptr++;
        if (!*bufptr)
          break;
      if (*bufptr != '&')
        continue;
    }
    length--;
  }

  /* Normalize in case we truncated in a wierd color so it doesn't bleed
*/

  *bufptr++ = '&';
  *bufptr++ = '0';

  /* Pad any remaining width with spaces */

  for(; length; length--)
    *bufptr++ = ' ';

  *bufptr = 0; /* Null terminate the string */

  return return_buf;
}


To use the function you need to provide it with a buffer to work with,
the following example assumes that the global buffer buf2 is not
currently being used, if it is you may need to change it or create your
own buffer.  To use the function you would change the line from your
example to the following...

sprintf(buf, "%s %d\r\n", color_truncate(string, 50, buf2), var);

Regards,


Peter


     +------------------------------------------------------------+
     | Ensure that you have read the CircleMUD Mailing List FAQ:  |
     |  http://qsilver.queensu.ca/~fletchra/Circle/list-faq.html  |
     +------------------------------------------------------------+



This archive was generated by hypermail 2b30 : 12/15/00 PST