NAME

sprintf - print to a string

sprintf, vsprintf - string print formatted

LIBRARY

Standard C library (libc, -lc)

SYNOPSIS

Header File

#include <stdio.h>

Prototype

int sprintf(char *str, const char *format, ...);

Note that ... represents zero or more additional arguments.

#include <stdio.h>
int sprintf(char *restrict str,
 const char *restrict format, ...);
int vsprintf(char *restrict str,
 const char *restrict format, va_list ap);

Feature Test Macro Requirements for glibc (see feature_test_macros(7)):

snprintf(), vsnprintf():

    _XOPEN_SOURCE >= 500 || _ISOC99_SOURCE
        || /* glibc <= 2.19: */ _BSD_SOURCE

DESCRIPTION

This function prints a “formatted string” to a location in memory. It expects as input the address of a buffer (which must be large enough to fit the string, including its \0), a “format string” that specifies what to print, and zero or more subsequent arguments. The format string can optionally contain “conversion specifications,” placeholders that begin with % that specify how to format the function’s subsequent arguments, if any. For instance, if buffer is an array of (at least) 13 bytes and i is 50, this function could format a string as follows:

sprintf(buffer, "This is CS%i", i);

Among this function’s supported conversion specifications are:

Conversion Specification Type
%c char
%f double
%f float
%i int
%li long
%s char *

To print an actual percent sign, use %%.

To specify the “precision” of a float or a double, %f can optionally contain a . after the % followed by a number of decimal places. For instance, this function could format the value of one third to one decimal place using %.1f, assuming buffer is an array of size 4 (at least):

sprintf(buffer, "%.1f\n", 1.0 / 3.0);

These functions are equivalent to snprintf(3) and vsnprintf(3), except that no check for buffer overrun is performed (see BUGS below).

ATTRIBUTES

For an explanation of the terms used in this section, see attributes(7).

Interface Attribute Value

sprintf(), vsprintf()

Thread safety MT-Safe locale

STANDARDS

C11, POSIX.1-2008.

HISTORY

C89, POSIX.1-2001.

BUGS

See printf(3).

sprintf(), vsprintf()

Because sprintf() and vsprintf() assume an arbitrarily long string, callers must be careful not to overflow the actual space; this is often impossible to assure. Note that the length of the strings produced is locale-dependent and difficult to predict. Use snprintf() and vsnprintf() instead (or asprintf(3) and vasprintf(3)).

SEE ALSO

asprintf(3), snprintf(3)

EXAMPLES

#include <stdio.h>
int main(void) { char buffer[13]; int i = 50; sprintf(buffer, "This is CS%i", i); printf("%s\n", buffer); float f = 50.0; sprintf(buffer, "This is CS%.0f", f); printf("%s\n", buffer); }