D
david.chanters
Hi all,
I am sure this is going to be another of me "close, keep trying, no
cigar" type questions -- as with all my others I have learnt tons, so
I will say thanks in advance.
I'm trying to do some string interpolation -- that is, expand certain
placeholders for other values, much like sprintf() does. Here's an
example:
static char* expand(const char *format)
{
char string[4096];
char *toReturn;
while (*format)
{
fprintf(stderr, "Looking at: %s\n", format);
int pos;
/* Until we find a % character. */
for (pos = 0; format[pos] && format[pos] != '%'; pos++);
/* Copy everything up to this into string. */
strncat(string, format, pos);
/* Advance where we're looking in format to that point. */
format += pos;
/* And try again if we have no percent character. */
if (*format != '%')
continue;
fprintf(stderr, "Before switch: %s\n", string);
format++;
switch (*format)
{
case 'n':
strcat(string, "Name");
break;
case 'c':
strcat(string, "County level address");
break;
case 'r':
strcat (string, "Restrictions");
break;
default:
break;
}
if (*format)
format++;
}
toReturn = string;
fprintf(stderr, "I am sending back: %s\n", toReturn);
return toReturn;
}
expand( "David (%n) --> Valued: [%c]" );
But as the debug via fprintf()s inside expand() shows, it seems to be
going beyonf (I assume) the NUL character -- since it reaches a point
of correctly exanding the string and keeps on going -- which isn't
right.
So any ideas much appreciated.
David
I am sure this is going to be another of me "close, keep trying, no
cigar" type questions -- as with all my others I have learnt tons, so
I will say thanks in advance.
I'm trying to do some string interpolation -- that is, expand certain
placeholders for other values, much like sprintf() does. Here's an
example:
static char* expand(const char *format)
{
char string[4096];
char *toReturn;
while (*format)
{
fprintf(stderr, "Looking at: %s\n", format);
int pos;
/* Until we find a % character. */
for (pos = 0; format[pos] && format[pos] != '%'; pos++);
/* Copy everything up to this into string. */
strncat(string, format, pos);
/* Advance where we're looking in format to that point. */
format += pos;
/* And try again if we have no percent character. */
if (*format != '%')
continue;
fprintf(stderr, "Before switch: %s\n", string);
format++;
switch (*format)
{
case 'n':
strcat(string, "Name");
break;
case 'c':
strcat(string, "County level address");
break;
case 'r':
strcat (string, "Restrictions");
break;
default:
break;
}
if (*format)
format++;
}
toReturn = string;
fprintf(stderr, "I am sending back: %s\n", toReturn);
return toReturn;
}
expand( "David (%n) --> Valued: [%c]" );
But as the debug via fprintf()s inside expand() shows, it seems to be
going beyonf (I assume) the NUL character -- since it reaches a point
of correctly exanding the string and keeps on going -- which isn't
right.
So any ideas much appreciated.
David