+ 1

how does sprintf work?

how does sprintf really work? how to use it? what does it do? when is it better to use it?

12th Nov 2018, 2:19 PM
Zaira Haram
Zaira Haram - avatar
1 Answer
+ 4
Prototype: int sprintf(char *buffer, const char *format, ... ); Loads the data from the given locations, converts them to character string equivalents and writes the results to a character string buffer.š IMPORTANT: The behavior is undefined if the string to be written (plus the terminating null character) exceeds the size of the array pointed to by buffer. "when is it better to use it?" For example, when you have a variety of inputs and need to store them in a buffer as C-string. Example ²: #include <stdio.h> int main () { char buffer [50]; // must be big enough to hold the following sequence of characters int n, a = 5, b = 3; n = sprintf (buffer, "%d plus %d is %d", a, b, a+b); printf ("[%s] is a string %d chars long\n", buffer, n); } Output: [5 plus 3 is 8] is a string 13 chars long Note that in the above example `sprintf` has nothing to do with standard output, however, it goes hand in hand with `printf` to direct the buffer's content to output. ___ š https://en.cppreference.com/w/c/io/fprintf ² http://www.cplusplus.com/reference/cstdio/sprintf/
12th Nov 2018, 2:44 PM
Babak
Babak - avatar