X
Xcriber51
Hi
The idiom of updating a value by adding something to it is so common that
some programming languages support it at the level of strings, such as;
s = "_";
s = s + "c"; // s == "_c"
s = s + "o"; // s == "_co"
etc.
C, being more "honest" (or, if you're unable to appreciate that, more
"cumbersome") on strings, doesn't provide such a facility. So, I'm trying
to emulate it by using the "sprintf" standard library function. (Original
idea, I know.) But it isn't behaving as expected.
Consider the following routine:
void _concat()
{
char *s;
s = "_";
sprintf(s,"%s%c",s,'c');
sprintf(s,"%s%c",s,'o');
sprintf(s,"%s%c",s,'n');
sprintf(s,"%s%c",s,'c');
sprintf(s,"%s%c",s,'a');
sprintf(s,"%s%c",s,'t');
printf("%s\n",s);
s = "t";
sprintf(s,"%c%s",'a',s);
sprintf(s,"%c%s",'c',s);
sprintf(s,"%c%s",'n',s);
sprintf(s,"%c%s",'o',s);
sprintf(s,"%c%s",'c',s);
sprintf(s,"%c%s",'_',s);
printf("%s\n",s);
}
Here, the first round of calls prints "_concat", as expected. The second,
however, outputs "_______".
Why?
Please keep it short, and I'm not interested in suggestions for
alternatives. Just a technical reply on why switching the place of the
format specifiers for character and string yields this asymmetrical
result.
Thanks!
-- K
The idiom of updating a value by adding something to it is so common that
some programming languages support it at the level of strings, such as;
s = "_";
s = s + "c"; // s == "_c"
s = s + "o"; // s == "_co"
etc.
C, being more "honest" (or, if you're unable to appreciate that, more
"cumbersome") on strings, doesn't provide such a facility. So, I'm trying
to emulate it by using the "sprintf" standard library function. (Original
idea, I know.) But it isn't behaving as expected.
Consider the following routine:
void _concat()
{
char *s;
s = "_";
sprintf(s,"%s%c",s,'c');
sprintf(s,"%s%c",s,'o');
sprintf(s,"%s%c",s,'n');
sprintf(s,"%s%c",s,'c');
sprintf(s,"%s%c",s,'a');
sprintf(s,"%s%c",s,'t');
printf("%s\n",s);
s = "t";
sprintf(s,"%c%s",'a',s);
sprintf(s,"%c%s",'c',s);
sprintf(s,"%c%s",'n',s);
sprintf(s,"%c%s",'o',s);
sprintf(s,"%c%s",'c',s);
sprintf(s,"%c%s",'_',s);
printf("%s\n",s);
}
Here, the first round of calls prints "_concat", as expected. The second,
however, outputs "_______".
Why?
Please keep it short, and I'm not interested in suggestions for
alternatives. Just a technical reply on why switching the place of the
format specifiers for character and string yields this asymmetrical
result.
Thanks!
-- K