C: sprintf inside printf as first argument

Studying C at university. This is not homework, but I tried to do something (some “creative” part of the assignment) and got stuck.

I understand that this is possible

printf("%d\n", printf("23.4")); // -> 23.44 (i.e. 23.4 + 4 bytes written)

but how can I use sprintf()as the first argument printf()?

sort of:

char * getFormatString(int n) {
   char * buffer;

   sprintf(buffer, "Value with %%d decimals is %%.%df", n);

   return buffer; 
}

void foo() {
   int decimals = 2;
   float pi = 3.141592;

   printf(getFormatString(decimals), decimals, pi);  // should output "Value with 2 decimals is 3.14"
}

Is it possible? So far, I am getting a seg error while executing it.

+3
source share
5 answers

Use sprintffor this purpose is vicious. Try instead:

printf("Value with %d decimals is %.*f", decimals, decimals, pi);
+6
source

First you must allocate memory for your buffer (and free it at the end):

char * buffer;
int decimals = 2;
float pi = 3.141592;

buffer = (char *) malloc(256); /* big enough buffer */
sprintf(buffer, "Value with %%d decimals is %%.%df", decimals);
printf(buffer, decimals, pi);

free(buffer);
+2
source

printf ,

printf("%d", printf("23.4")); // -> 23.44

sprintf , , printf, , , .

, , . - :

char buffer[1024];    // buffer has to be an actual string (or you could use malloc)
int decimals = 2;
float pi = 3.141592;

sprintf(buffer, "Value with %%d decimals is %%.%df", decimals);

printf(buffer, decimals, pi);
+2

segfault, sprintf - , ( buffer). malloc, :

buffer = malloc(100);

sprintf getFormatString. . , , getFormatString .

:

char *getFormatString(int n) {
    char *buffer = malloc(100);
    sprintf(buffer, "Value with %%d decimals is %%.%df", n);
    return buffer;
}

void foo() {
    int decimals = 2;
    float pi = 3.141592;
    char *fmtstr = getFormatString(decimals);
    printf(fmtstr, decimals, pi);  // should output "Value with 2 decimals is 3.14"
    free(fmtstr);
}
+1

printf() sprintf() int. .

int sprintf ( char * str, const char * format, ... );
int printf ( const char * format, ... );

You can use sprintf()as an argument for printf()if you want to print the number of characters written with sprintf().

0
source

Source: https://habr.com/ru/post/1768641/


All Articles