Course contentsShow
← C
Lesson 703 of 1,21910. Input and OutputFree lesson

Formatting strings in memory with sprintf

Formatting strings in memory with sprintf

What you'll learn: How to use sprintf to "print" formatted text into a string variable rather than to the console screen.

The Clipboard Analogy

Up until now, you have likely used printf to display information on your monitor. Think of printf like a megaphone: you speak into it, and the output is broadcast immediately for the world to see.

sprintf, on the other hand, is like a label maker. Instead of shouting the information into the air, you are printing it onto a sticky note (a buffer) so you can save it, move it around, or use it later in your program. The "s" in sprintf stands for string.

Why use it?

Sometimes you don't want to show data to the user yet. You might want to:

  • Build a complex filename (like image_01.png, image_02.png).
  • Combine a first and last name into a single "Full Name" variable.
  • Convert numbers into text so you can send them over a network.

How it works

The syntax is almost identical to printf, but it takes one extra argument at the very beginning: the destination array where the text will be stored.

#include <stdio.h>

int main() {
    char message[50]; // The "label" where we will store our text
    char name[] = "Alice";
    int level = 10;

    // Instead of printing to the screen, we store it in 'message'
    sprintf(message, "Hero: %s, Level: %d", name, level);

    // Now 'message' contains "Hero: Alice, Level: 10"
    // We can print it later, or do something else with it!
    printf("Stored string: %s\n", message);

    return 0;
}

A Word of Caution

When using sprintf, you are responsible for making sure your destination array is big enough to hold the resulting text. If you try to fit a 100-character sentence into a 10-character array, your program will crash or behave unpredictably (this is known as a buffer overflow). Always estimate the maximum possible size your string might need, including the invisible null terminator (\0) at the end!

Key takeaway

sprintf allows you to format text and store the result in a string variable for later use, rather than sending it directly to the output console.