I'm making a printlnf
function, that like printf
prints formatted text, but with an added newline at the end, problem is that the number I pass in, comes out as garbage.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdarg.h>
void printlnf(const char* input_string, ...) {
/* allocate with room for the newline */
char* fmt_str = malloc(strlen(input_string) + 2);
strcpy(fmt_str, input_string);
strcat(fmt_str, "\n");
/* print the string with the variable arguments */
va_list argptr;
va_start(argptr, input_string);
printf(fmt_str, argptr);
/* free everything */
va_end(argptr);
free(fmt_str);
}
int main(void) {
printlnf("This is a test of the printlnf");
printlnf("This is the %dnd line of the print", 2);
return 0;
}
The output is usually something along the lines of this:
This is a test of the printlnf
This is the 1415441184nd line of the print
How do I fix this?