how does sprintf work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 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. ___ ¹ ²
12th Nov 2018, 2:44 PM
Babak - avatar