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

Parsing data from strings with sscanf

Parsing data from strings with sscanf

What you'll learn: How to extract structured data like integers or floats from a plain string variable using the powerful sscanf function.

The Digital Sieve

In previous lessons, you used scanf to get data from the keyboard. But what if the data is already inside your program, trapped within a string? Imagine you have a single string that contains a person’s name and age, like "Alice 25". To your program, this is just a sequence of characters. To use that 25 for math, you need to pull it out and convert it into an integer.

This is where sscanf (the "s" stands for string) comes in. Think of it as a digital sieve. You pour your string through it, define the "holes" (formats) you want to catch, and the function sorts the pieces into the variables you provide.

How it works

The syntax for sscanf is almost identical to scanf, with one addition: the first argument is the name of the string you are reading from.

#include <stdio.h>

int main() {
    char data[] = "Temperature: 72 10/24/2023";
    char label[20];
    int degrees;
    int month, day, year;

    // We tell sscanf to look at 'data' and find a string, 
    // an integer, and three integers separated by slashes.
    sscanf(data, "%s %d %d/%d/%d", label, &degrees, &month, &day, &year);

    printf("The %s was %d degrees on day %d.", label, degrees, day);

    return 0;
}

In the example above, sscanf scans the data array. It ignores the spaces automatically, matches the literal slashes in the date format, and places the resulting values into our variables.

Why use it?

You might wonder why we don't just use scanf directly. In professional programming, reading directly from the keyboard is risky because users make mistakes. A common "best practice" is to read an entire line of input into a string first (using a function like fgets), validate that the string isn't empty or broken, and then use sscanf to parse the actual data. This gives you much more control over how your program handles messy information.

Key takeaway

Use sscanf to treat a string like an input source, extracting specific formatted values into variables.