Cher Cher - 2 months ago 25
C Question

Store printf in a char array?

is there a way to take the result of a

printf in a char array
?

I need to set a string P: result

where
result
is an
int


So if
result = 4;


So I need a
char array
containing
"S: 4"


Other methods are fine too, however I have my result in
printf
, so I wonder if I can just fetch it?

Answer

Yes, you can use snprintf (a safer alternative to sprintf). The only difference between snprintf and printf is that snprintf writes to a char * instead of directly to standard output:

#include <stdio.h>

int main(int argc, char *argv[])
{
    char buffer[128];
    int result = 4;

    snprintf(buffer, sizeof(buffer), "S: %d", result);

    printf("%s\n", buffer);
    return 0;
}