So the case was simple: I needed to add a character in front of a c string.
So I had my code:
char *a = "2233b";
char output[100];
char toAdd = '-';
strcpy(output, a);
printf("\noutput=%s", output);
sprintf(output, "%c%s", toAdd, a);
printf("\noutput=%s", output);
And the output was as expected:
output=2233b
output=-2233b
Ok, so far so good. Now the case changed and I wanted to add more characters before a c string, so I configured the code like so:
char *a = "2233b";
char output[100];
char toAdd = '-';
strcpy(output, a);
printf("\noutput=%s", output);
sprintf(output, "%c%s", toAdd, a);
printf("\noutput=%s", output);
sprintf(output, "%c%s", toAdd, output);
printf("\noutput=%s", output);
I expected the output to be:
output=2233b
output=-2233b
output=--2233b
But this was not the case and the following output was printed on my screen:
output=2233b
output=-2233b
output=-------
Why is does output
contain this value?
Because the format is just the character (%c
) toAdd
('-'
) and a string (%s
) which is output
and contains ("-2233b"
).
So why isn't the last output containing "--2233b"
? And how come the characters of output
are all converted to '-'
?