Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Store printf in a char array? [duplicate]

Tags:

c

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?

like image 930
Cher Avatar asked Dec 04 '22 23:12

Cher


2 Answers

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;
}
like image 122
Sean Bright Avatar answered Jan 06 '23 15:01

Sean Bright


You can use sprintf to get the formatted string.

http://www.tutorialspoint.com/c_standard_library/c_function_sprintf.htm

like image 32
Gabriel Avatar answered Jan 06 '23 14:01

Gabriel