A Little C Primer/The C sprintf Function

The "sprintf" function creates strings with formatted data. Technically speaking, this is part of the standard-I/O library, and requires the declaration:

   #include <stdio.h>

However, it is really a string function and needs to be discussed along with the other string functions. The syntax of "sprintf()" is exactly the same as it is for "printf()", except there is an extra parameter at the beginning, which is a pointer to a string. Instead of outputting to standard output, sprintf outputs to the string. For example:

   /* csprntf.c */

   #include <stdio.h>

   int main()
   {
      char b[100];
      int i = 42;
      float f = 1.1234f;
      sprintf( b, "Formatted data:  %d / %f", i, f );
      puts( b );
   }

—prints the string:

   Formatted data:  42 / 1.1234

There is also an "sscanf()" function that similarly mirrors "scanf()" functionality.

C STRING FUNCTION LIBRARY edit

moved to A Little C Primer/C String Function Library