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
sscanfand scan sets like%[^,] - Using
%nto 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 likeprintfbut writes intobuf, never more thansizebytes including the final'\0'.%03dpads the roll number with zeros to 3 digits, and%.2frounds 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 + usedwith the space that remains, and stop if a piece would not fit. - Width and alignment work as in
printf:%-8sleft-aligns,%8sright-aligns,%06.1fpads with zeros and%xprints 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
sscanfreturns 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.%lfreads adouble; plain%finscanf-family functions is forfloat.%nstores 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
| Function | Does | Safety |
|---|---|---|
sprintf(buf, fmt, ...) | Format into a buffer | No size limit: can overflow |
snprintf(buf, n, fmt, ...) | Format into a buffer of n bytes | Safe; returns the needed length |
sscanf(str, fmt, ...) | Parse values from a string | Safe if every %s/%[ has a width |
vsnprintf(buf, n, fmt, args) | snprintf with a va_list | For writing your own variadic helpers |
Common Mistakes
- Using
sprintfwith input whose length you do not control. - Not checking the return value of
snprintforsscanf. - Using
%sinsscanfwithout a width, which can overflow the destination. - Passing a value instead of an address to
sscanf: write&age, notage. Arrays such asnameare 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
snprintfformats into a buffer without overflowing it.- A return value of at least the buffer size means truncation.
sscanfreturns the number of values matched; always check it.- Give every
%sand%[a width.
