CodeBlanks Logo Icon CodeBlanks

sprintf

Learn to build formatted strings with sprintf.

sprintf: formatted writing to a string

The sprintf function works like printf but writes the result into a string buffer instead of the screen. It comes with the <stdio.h> header. Its signature is int sprintf(char *buf, const char *fmt, ...).

char buf[64];
int age = 25;
sprintf(buf, "Age: %d", age);
// buf = "Age: 25"

The first argument is the target buffer, the second is the format string, and the rest are values. The return value is the number of characters written. You must make sure the buffer is large enough; otherwise a memory overflow occurs.

Joining text with sprintf

With sprintf you can join several pieces into a single string. It is like printf writing into a buffer instead of the screen.

char buf[128];
char *name = "Ayse";
int score = 95;
sprintf(buf, "Player: %s, Score: %d", name, score);
printf("%s\n", buf);

Here name and score become a single string. You can also use the return value of sprintf to learn the length written. This is the cleanest way to join many pieces in one line.

Practice Fill a buffer with the age info

Define a char buf[64] buffer. Use sprintf to write int age = 25 into the buffer as "Age: 25". Then print the buffer with printf.

Starter code

main.c
#include <stdio.h>

int main(void) {
    int age = 25;
    /* Define a buffer; write the age with sprintf; print with printf */
    return 0;
}

Sample solution

main.c
char buf[64];
sprintf(buf, "Age: %d", age);
printf("%s\n", buf);

Expected output

Age: 25

Questions and answers

Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.

1 Fill in the blank: sprintf call

Question
char buf[64];
int age = 25;
____(buf, "Age: %d", age);
Answer
char buf[64];
int age = 25;
sprintf(buf, "Age: %d", age);

Explanation: sprintf writes into a buffer.

2 Match format specifier to type

Term Meaning
%d int
%s string
%f double
%c char

3 What does the sprintf call return?

  • The written string
  • A pointer
  • An error code
  • The number of characters written Correct answer

Explanation: sprintf returns the number of characters written.

All lessons in Beginner