I\'d like to do something like printf(\"?\", count, char)
to repeat a character count
times.
What is the right format-string to accomplish
printf("%.*s\n",n,(char *) memset(buffer,c,n));
n
<= sizeof(buffer)
[ maybe also n < 2^16]
However the optimizer may change it to puts(buffer)
and then the lack of EoS will .....
And the assumption is that memset is an assembler instruction (but still a loop be it on chip).
Strictly seen there is no solution given you precondition 'No loop'.
i think doing some like this.
void printchar(char c, int n){
int i;
for(i=0;i<n;i++)
print("%c",c);
}
printchar("*",10);
In c++ you could use std::string to get repeated character
printf("%s",std::string(count,char).c_str());
For example:
printf("%s",std::string(5,'a').c_str());
output:
aaaaa
Short answer - yes, long answer: not how you want it.
You can use the %* form of printf, which accepts a variable width. And, if you use '0' as your value to print, combined with the right-aligned text that's zero padded on the left..
printf("%0*d\n", 20, 0);
produces:
00000000000000000000
With my tongue firmly planted in my cheek, I offer up this little horror-show snippet of code.
Some times you just gotta do things badly to remember why you try so hard the rest of the time.
#include <stdio.h>
int width = 20;
char buf[4096];
void subst(char *s, char from, char to) {
while (*s == from)
*s++ = to;
}
int main() {
sprintf(buf, "%0*d", width, 0);
subst(buf, '0', '-');
printf("%s\n", buf);
return 0;
}
If you have a compiler that supports the alloca() function, then this is possible solution (quite ugly though):
printf("%s", (char*)memset(memset(alloca(10), '\0', 10), 'x', 9));
It basically allocates 10 bytes on the stack which are filled with '\0' and then the first 9 bytes are filled with 'x'.
If you have a C99 compiler, then this might be a neater solution:
for (int i = 0; i < 10; i++, printf("%c", 'x'));
char buffer[41];
memset(buffer, '-', 40); // initialize all with the '-' character<br /><br />
buffer[40] = 0; // put a NULL at the end<br />
printf("%s\n", buffer); // show 40 dashes<br />