Cher Cher - 1 year ago 117
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?

Answer Source

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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download