Name

sprintf

Synopsis

Stores formatted output in a string buffer

#include <stdio.h>
intsprintf( char * restrict dest, const char * restrict format, ... );

The sprintf() function is similar to snprintf(), except that it has no parameter to limit the number of characters written to the destination buffer. As a result, using it means risking buffer overflows, especially because the length of the output depends on the current locale as well as input variables. Use snprintf() instead.

Example

double x = 1234.5, y = 678.9, z = -753.1, a = x * y + z;
char buffer[80];
int output_len = 0;

output_len =sprintf( buffer, "For the input values %lf, %lf, and %lf, "
                       "the result was %lf.\n",
                       x, y, z, a );
puts( buffer );
if ( output_len >= 80 )
  fprintf( stderr, "Output string overflowed by %d characters.\n"
                   "The variables x, y, z and a may have been corrupted:\n"
                   "x now contains %lf, y %lf, z %lf, and a %lf.\n",
                    output_len - 79, x, y, z, a );

This code produces the following output:

For the input values 1234.500000, 678.900000, and -753.100000, the result was 
837348.950000.

Output string overflowed by 14 characters.
The variables x, y, z and a may have been corrupted:
x now contains 1234.500000, y 678.900000, z -736.004971, and a 0.000000.

See Also

printf(), fprintf(), snprintf(), declared in stdio.h; vprintf(), vfprintf(), vsprintf(), vsnprintf(), declared in stdarg.h; the wide-character functions: wprintf(), fwprintf(), swprintf(), declared in stdio.h and wchar.h; and vwprintf(), vfwprintf(), and vswprintf() ...

Get C in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.