I am looking to create a function that returns a string from format and the variable argument list. Something like:
const char* strfmt(char *format, ...);
It seems to me that there ought to be a way to format a string and replace with the appropriate arguments and return the result. The closest I've seen still prints to the console (stdout):
void minimal_printf(char *fmt, ...) {
va_list ap;
char *p, *sval;
int ival;
double dval;
va_start(ap, fmt);
for (p = fmt; *p; p++) {
if (*p != '%') {
putchar(*p);
continue;
}
switch (*++p) {
case 'd':
ival = va_arg(ap, int);
printf("%d", ival);
break;
case 'f':
dval = va_arg(ap, double);
printf("%f", dval);
break;
case 's':
for (sval = va_arg(ap, char *); *sval; sval++)
putchar(*sval);
break;
default:
putchar(*p);
break;
}
}
va_end(ap);
}
Also looks like the loop doesn't end correctly. Running this in my debugger causes a it to exit with an error code after 5 seconds:
(Process terminated with status -1073741819 (0 minute(s), 5 second(s))
I'm not so concerned about the looping issue because this isn't the solution I'll use in the end.
How do we not have a function that does this?