Cher Cher - 6 months ago 62
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

is an

So if
result = 4;

So I need a
char array
"S: 4"

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


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;