5

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?

2
  • 1
    You can use sprintf, which writes into a char buffer? Make sure your buffer is big enough (expected length + 1 for the nul terminator) Commented Sep 14, 2016 at 16:17
  • 1
    Look up sprintf Commented Sep 14, 2016 at 16:17

2 Answers 2

13

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; } 
Sign up to request clarification or add additional context in comments.

3 Comments

The result of snprintf should be checked to see if a larger buffer was required, or some other error occurred.
The buffer size was chosen to have sufficient room for the known inputs. The maximum length of the rendered string is 13 characters. Other error checking was omitted for brevity.
Sorry, my comment should have begun with "Generally speaking, ...".
4

You can use sprintf to get the formatted string.

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

6 Comments

It is too easy to cause buffer overrun with sprintf. snprintf is better, since buffer overrun is caused by the programmer telling the function the buffer is bigger than it actually is.
@jxh Using snprintf() like in another answer is not much better than this answer. It trades a bad problem (potential buffer overflow in the general case) with an undetected wrong result. Using snprintf() too often conveys a false sense of "safety" when the result of snprintf() is not checked.
@chux: The safety is real so long as the buffer size is correct. The wrong result is truncated output, which is not usually a showstopper when the output is intended for display. But checking success of functions that can fail is just SOP, and something code review and static code analysis tools should be able to find.
@jxh The safety is real for sprintf() too so long as the buffer size is correct. The "which is not usually a showstopper" is the false sense of safety of my comment. char s[16], sprintf(s, sizeof s, "Target is %d %d", lat, lon); cmd(s); Agree snprintf() with result checking should be SOP.
@chux: GNU provides asprintf for that.
|

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.