0
0
CHow-ToBeginner · 3 min read

How to Use sprintf in C: Syntax, Example, and Tips

In C, sprintf formats data and stores it as a string in a buffer. You provide a buffer, a format string, and values to insert, and sprintf writes the formatted result into the buffer.
📐

Syntax

The sprintf function writes formatted data to a string buffer. Its syntax is:

int sprintf(char *str, const char *format, ...);
  • str: The buffer where the formatted string is stored.
  • format: A string that specifies how to format the data, using placeholders like %d for integers or %s for strings.
  • ...: The values to insert into the format string.

The function returns the number of characters written (excluding the null terminator).

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

Example

This example shows how to use sprintf to format an integer and a string into a buffer.

c
#include <stdio.h>

int main() {
    char buffer[100];
    int age = 25;
    const char *name = "Alice";

    sprintf(buffer, "Name: %s, Age: %d", name, age);
    printf("%s\n", buffer);

    return 0;
}
Output
Name: Alice, Age: 25
⚠️

Common Pitfalls

Common mistakes when using sprintf include:

  • Not allocating enough space in the buffer, which can cause buffer overflow and crashes.
  • Forgetting that sprintf does not check buffer size, so use snprintf for safer formatting.
  • Using wrong format specifiers that don't match the data type, causing incorrect output or runtime errors.
c
#include <stdio.h>

int main() {
    char smallBuffer[10];
    int number = 12345;

    // Unsafe: buffer too small, can overflow
    // sprintf(smallBuffer, "%d", number);

    // Safe alternative:
    snprintf(smallBuffer, sizeof(smallBuffer), "%d", number);
    printf("%s\n", smallBuffer);

    return 0;
}
Output
12345
📊

Quick Reference

Format SpecifierDescriptionExample
%dInteger number42
%sString"Hello"
%fFloating-point number3.14
%cSingle character'A'
%%Literal percent sign%

Key Takeaways

Use sprintf to format data into a string buffer with a format string and values.
Always ensure the buffer is large enough to avoid overflow; consider using snprintf for safety.
Match format specifiers correctly to the data types to prevent errors.
sprintf returns the number of characters written, excluding the null terminator.
Remember that sprintf does not check buffer size, so use it carefully.