In C, what function writes formatted output to a string?

The story behind the answer

In C, the function that writes formatted output to a string is `sprintf`.

`sprintf` belongs to the printf family of functions in the C standard library. It takes a destination character array, a format string, and additional values, then builds formatted text in that array. For example, `sprintf(buffer, "Score: %d", score);` writes the resulting characters into `buffer`, including a terminating null character when successful.

The common mix-up is with the related functions. `printf` writes to standard output, usually the terminal, while `fprintf` writes to a specified stream such as a file. `snprintf` also writes to a string, but accepts a maximum buffer size and is generally safer because it can limit how many characters are written.

Because `sprintf` does not know the destination buffer's capacity, oversized output can cause a buffer overflow and create security vulnerabilities. Modern C programs commonly prefer `snprintf` when a bounded write is appropriate. The family name comes from “print formatted,” even when the destination is memory rather than a printer or screen.

Source: Wikipedia · fact-checked Aug. 2026

Add question to a list

Choose a list to keep this question in: