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?
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;
}
You can use sprintf
to get the formatted string.
http://www.tutorialspoint.com/c_standard_library/c_function_sprintf.htm
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With