Reading history

snprintf, sprintf and sscanf in C

6 min read 3 views

Format strings safely with snprintf, detect truncation, build strings in steps, and parse values with sscanf scan sets and %n, with tested C examples.

printf writes formatted text to the screen and scanf reads formatted input. Their string versions do the same jobs on memory: snprintf builds a formatted string in a buffer, and sscanf pulls values out of a string. Together they let you create file names, messages and records, and parse dates, commands and CSV lines. This lesson shows how to use them safely, including the older sprintf and why to avoid it.

In this lesson you will learn

  • Formatting into a buffer with snprintf
  • Detecting truncation from the return value
  • Building a string piece by piece
  • Parsing strings with sscanf and scan sets like %[^,]
  • Using %n to walk through a string

You should know printf and scanf and strings.

Formatting with snprintf

#include <stdio.h>
#include <string.h>

int main(int argc, char *argv[]) {
    (void)argv;
    char buf[64];

    /* snprintf formats into a buffer and never writes past its size */
    int len = snprintf(buf, sizeof buf, "Roll %03d: %s, CGPA %.2f", 7, "Tania", 3.948);
    printf("[%s] (%d chars)\n", buf, len);

    /* Building a string step by step: keep track of the used length */
    char line[40];
    size_t used = 0;
    const int marks[] = {88, 92, 79, 95};
    for (int i = 0; i < 4; i++) {
        int n = snprintf(line + used, sizeof line - used, i ? ", %d" : "%d", marks[i]);
        if (n < 0 || (size_t)n >= sizeof line - used) break;   /* would not fit */
        used += (size_t)n;
    }
    printf("marks: %s\n", line);

    /* A too-small buffer: output is cut, and the return value says how long it wanted to be */
    char tiny[8];
    const char *country = argc > 99 ? "BD" : "Bangladesh";   /* chosen at run time */
    int need = snprintf(tiny, sizeof tiny, "%s %d", country, 2026);
    printf("tiny = [%s], needed %d chars, truncated: %s\n",
           tiny, need, need >= (int)sizeof tiny ? "yes" : "no");

    /* Width, padding and alignment work just like printf */
    snprintf(buf, sizeof buf, "|%-8s|%8s|%06.1f|%x|", "left", "right", 3.14159, 255);
    printf("%s\n", buf);
    return 0;
}

Output

[Roll 007: Tania, CGPA 3.95] (26 chars)
marks: 88, 92, 79, 95
tiny = [Banglad], needed 15 chars, truncated: yes
|left    |   right|0003.1|ff|
  • snprintf(buf, size, format, ...) works like printf but writes into buf, never more than size bytes including the final '\0'.
  • %03d pads the roll number with zeros to 3 digits, and %.2f rounds the CGPA to 3.95.
  • The return value is the length the full text would have had. If it is greater than or equal to the buffer size, the output was truncated: “Bangladesh 2026” needed 15 characters, so only “Banglad” fit in 8 bytes.
  • To build a string in steps, write at line + used with the space that remains, and stop if a piece would not fit.
  • Width and alignment work as in printf: %-8s left-aligns, %8s right-aligns, %06.1f pads with zeros and %x prints hexadecimal.
  • The country name is chosen at run time in this example only because GCC can spot a guaranteed truncation at compile time and warn about it.

Parsing with sscanf

#include <stdio.h>

int main(void) {
    /* sscanf reads values out of a string; its return value is the number matched */
    const char *record = "Nusrat,CSE,3.82,21";
    char name[20], dept[10];
    double cgpa;
    int age;
    int n = sscanf(record, "%19[^,],%9[^,],%lf,%d", name, dept, &cgpa, &age);
    printf("matched %d: name=%s dept=%s cgpa=%.2f age=%d\n", n, name, dept, cgpa, age);

    /* Parsing a date and checking every field was read */
    int d, m, y;
    const char *dates[] = {"26/03/2026", "26-03-2026", "31/12"};
    for (int i = 0; i < 3; i++) {
        if (sscanf(dates[i], "%d/%d/%d", &d, &m, &y) == 3)
            printf("%-10s -> day %d, month %d, year %d\n", dates[i], d, m, y);
        else
            printf("%-10s -> not a dd/mm/yyyy date\n", dates[i]);
    }

    /* %n records how many characters were consumed */
    const char *cmd = "move 15 north";
    char verb[10], dir[10];
    int steps, used;
    if (sscanf(cmd, "%9s %d %9s%n", verb, &steps, dir, &used) == 3)
        printf("%s %d steps %s (read %d chars)\n", verb, steps, dir, used);

    /* Reading several numbers from one line */
    const char *line = "  10 20 30 x 40";
    int value, offset = 0, consumed, total = 0;
    while (sscanf(line + offset, "%d%n", &value, &consumed) == 1) {
        total += value;
        offset += consumed;
    }
    printf("sum before the first non-number: %d\n", total);
    return 0;
}

Output

matched 4: name=Nusrat dept=CSE cgpa=3.82 age=21
26/03/2026 -> day 26, month 3, year 2026
26-03-2026 -> not a dd/mm/yyyy date
31/12      -> not a dd/mm/yyyy date
move 15 steps north (read 13 chars)
sum before the first non-number: 60
  • sscanf returns how many values it matched. Comparing that with the number you expected is the only reliable way to know the parse worked: the second and third dates failed because the result was not 3.
  • %19[^,] is a scan set meaning “up to 19 characters that are not commas”. It reads fields that contain spaces, and the width keeps the result inside the 20-byte array. The commas in the format then match the commas in the text.
  • %lf reads a double; plain %f in scanf-family functions is for float.
  • %n stores how many characters have been consumed so far; it is not counted in the return value.
  • Adding the consumed count to an offset lets a loop read one number after another, stopping cleanly at the first non-number.

Formatted String Functions

FunctionDoesSafety
sprintf(buf, fmt, ...)Format into a bufferNo size limit: can overflow
snprintf(buf, n, fmt, ...)Format into a buffer of n bytesSafe; returns the needed length
sscanf(str, fmt, ...)Parse values from a stringSafe if every %s/%[ has a width
vsnprintf(buf, n, fmt, args)snprintf with a va_listFor writing your own variadic helpers

Common Mistakes

  1. Using sprintf with input whose length you do not control.
  2. Not checking the return value of snprintf or sscanf.
  3. Using %s in sscanf without a width, which can overflow the destination.
  4. Passing a value instead of an address to sscanf: write &age, not age. Arrays such as name are already addresses.

Practice Exercises

Exercise 1. Build the file name report_2026_03.txt from the integers year and month.

Show answer
char fname[32];
int year = 2026, month = 3;
snprintf(fname, sizeof fname, "report_%d_%02d.txt", year, month);

Exercise 2. Parse the time "14:05:30" into hours, minutes and seconds, and print the total seconds.

Show answer
int h, m, s;
if (sscanf("14:05:30", "%d:%d:%d", &h, &m, &s) == 3)
    printf("%d seconds\n", h * 3600 + m * 60 + s);   /* 50730 seconds */

Frequently Asked Questions

How can I find out how big a buffer I need before formatting?

Call snprintf(NULL, 0, fmt, ...). It writes nothing and returns the number of characters needed. Allocate that plus one byte for '\0', then format again into the new buffer.

Is sscanf good for parsing CSV files?

It is fine for simple lines with no empty fields and no quoted commas. For general CSV, split the line manually or use a small parser, because %[^,] fails on an empty field.

Summary

  • snprintf formats into a buffer without overflowing it.
  • A return value of at least the buffer size means truncation.
  • sscanf returns the number of values matched; always check it.
  • Give every %s and %[ a width.

Next: Splitting Strings with strtok in C.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *