What is sscanf in C Explained- C Programming Course Online

🚀 Learn BLE on Linux (BlueZ) – Programming Part 1

Hands-on Bluetooth Low Energy course. Special price: ₹399

Enroll Now on Udemy →
💬 Need help or career guidance? Ask us!Contact Us →

Free C Programming Course · Strings

sscanf in C Explained

Parse numbers, hex values and packets out of text with the standard library, safely.

Sooner or later every embedded program has to read numbers out of text: a modem reply, a line from a log, a command typed on a serial console. sscanf in C is the standard library function built for that job. It reads formatted data from a string that already sits in memory and converts it into integers, floats, hex values and smaller strings. This lecture of our free C programming course shows how it works, why its return value matters, and where it fits in embedded C programming, with original programs you can compile and run on any Linux laptop.

What You Will Learn

  • What sscanf in C does and how it differs from scanf and sprintf
  • How a format string maps pieces of text to variables
  • Why the return value of sscanf decides whether your data is trustworthy
  • How to parse hexadecimal register commands, timestamps and sensor packets
  • How to fill a struct from a text line
  • Which mistakes crash real firmware and how to avoid them

Prerequisites

You should be comfortable with character arrays, the null terminator, pointers to char and the basic scanf and printf specifiers from the earlier lectures of this free C tutorial. If & (address of) still feels unclear, revisit the pointers chapter first, because sscanf stores its results through addresses.

What sscanf in C Actually Does

The prototype, from the C standard library header stdio.h, is:

int sscanf(const char *restrict s, const char *restrict format, ...);

Think of it as scanf with a different data source. scanf pulls characters from the keyboard stream (stdin). sscanf pulls them from the string you hand it as the first argument. Everything else, the format string, the conversion specifiers and the address arguments, works the same way. It is also the mirror image of sprintf and snprintf from the previous lecture: those turn typed values into text, sscanf turns text back into typed values.

Two details are worth noticing in the prototype. The source string is declared const char *, so sscanf will never modify it, and you can safely feed it a string literal. The trailing ... means you pass one address for every conversion in the format string.

sscanf in C: text in memory to typed variables
Source string held in RAM (never touched by sscanf)
ADC1space2048space3.30
format string: %7s %d %f
%7s%d%f
converted and stored through the addresses you pass
char channel[8]int rawfloat vref
return value = how many fields were stored (here 3)

Your First sscanf in C Program

Imagine a debug UART that prints one line per ADC sample: the channel name, the raw 12-bit count and the reference voltage. Save the following as sensor_line.c.

#include <stdio.h>

int main(void)
{
    const char *line = "ADC1 2048 3.30";
    char  channel[8];
    int   raw;
    float vref;

    int n = sscanf(line, "%7s %d %f", channel, &raw, &vref);

    printf("fields converted : %d\n", n);
    printf("channel          : %s\n", channel);
    printf("raw count        : %d\n", raw);
    printf("reference volts  : %.2f\n", vref);
    return 0;
}

Compile and run it:

gcc -std=c17 -Wall -Wextra -o sensor_line sensor_line.c
./sensor_line

Expected output:

fields converted : 3
channel          : ADC1
raw count        : 2048
reference volts  : 3.30

Walk through the format string "%7s %d %f" from left to right:

  • %7s reads a run of non-space characters, but at most seven of them. The array holds eight bytes, so one byte is always left for the terminating null.
  • The blank in the format is not a literal space. It means “skip any amount of white space, including none”.
  • %d reads a decimal integer and stores it through &raw.
  • %f reads a floating-point number and stores it through &vref, which must therefore be a float. A double needs %lf.

Notice that channel has no & in front of it. An array name already decays to the address of its first element, so adding another & is a classic beginner mistake.

Check the Return Value of sscanf

sscanf returns the number of fields it successfully converted and stored. That number is the only honest report of what happened. It returns EOF (a negative value) only when the input ends before the first conversion could even start. If a field does not match, scanning stops right there and every later variable keeps whatever it held before the call.

Return valueMeaningWhat your code should do
Equal to the number of conversions in the formatEvery field matched and was storedUse the values
Smaller, but at least 1Partial success, scanning stopped at a mismatchTreat the whole line as bad input
0The very first field did not matchReject the line
EOFEmpty or exhausted input before any conversionReject the line

The next program parses a clock stamp with literal colons in the format, then feeds sscanf a broken line to show the partial-success case.

#include <stdio.h>

int main(void)
{
    const char *stamp = "14:05:59";
    int hh = 0, mm = 0, ss = 0;

    int n = sscanf(stamp, "%d:%d:%d", &hh, &mm, &ss);
    printf("converted %d fields -> %02d h %02d m %02d s\n", n, hh, mm, ss);
    printf("seconds since midnight = %d\n", hh * 3600 + mm * 60 + ss);

    const char *bad = "ADC1 xyz";
    char tag[8] = "";
    int  count  = -1;

    n = sscanf(bad, "%7s %d", tag, &count);
    printf("bad line: converted %d, tag=%s, count=%d\n", n, tag, count);
    return 0;
}
converted 3 fields -> 14 h 05 m 59 s
seconds since midnight = 50759
bad line: converted 1, tag=ADC1, count=-1
Where sscanf stops reading: “ADC1 xyz” with %7s %d
ADC1spacexyz
%7s matches ADC1%d fails on x
scanning stops at the first mismatch, return value = 1
tag = ADC1count = unchanged

Initialise your variables. In the bad-line test, count kept its starting value of -1 because %d never matched. If you had left it uninitialised you would have printed garbage and not known why.

Literal characters in the format

In "%d:%d:%d" the colons are literal. sscanf expects to find exactly a colon in the input at that position, consumes it, and carries on. If the text has a dash instead, the match fails at that point and the return value tells you how far it got. This is how you make a format string act as a tiny grammar for your data.

Parsing Hex Values and Register Commands

Embedded work is full of hexadecimal. The %x specifier reads an unsigned hexadecimal number and accepts the 0x prefix, so the same format handles both 1F and 0x1F. A serial console that lets an engineer poke a peripheral register is a perfect example.

#include <stdio.h>

int main(void)
{
    const char *cmd = "REG=0x40021000 VAL=0xFF";
    unsigned int reg = 0;
    unsigned int val = 0;

    int n = sscanf(cmd, "REG=%x VAL=%x", &reg, &val);

    if (n == 2)
        printf("address=0x%08X  value=0x%02X  (%u decimal)\n", reg, val, val);
    else
        printf("could not parse register command\n");
    return 0;
}
address=0x40021000  value=0xFF  (255 decimal)

The literal text REG= and VAL= in the format must match the input exactly, which already filters out most malformed commands. Here is a quick reference for the specifiers you will use most.

SpecifierArgument typeReads
%dint *Signed decimal
%uunsigned int *Unsigned decimal
%xunsigned int *Hexadecimal, 0x optional
%ldlong *Signed decimal, long
%ffloat *Floating-point
%lfdouble *Floating-point, double
%schar * (array)Non-space characters, add a width
%cchar *Exactly one character, spaces included

Filling a struct From a Text Packet

Wireless sensor nodes often send readable packets: an identifier, a sequence number and a measurement. A struct is the natural home for the parsed result, and each member’s address goes straight into sscanf.

#include <stdio.h>

struct reading {
    char  node[8];
    int   seq;
    float celsius;
};

int main(void)
{
    const char *packet = "node7 42 -3.5";
    struct reading r;

    int n = sscanf(packet, "%7s %d %f", r.node, &r.seq, &r.celsius);
    if (n != 3) {
        puts("malformed packet");
        return 1;
    }

    printf("node    : %s\n", r.node);
    printf("seq     : %d\n", r.seq);
    printf("celsius : %.1f\n", r.celsius);
    return 0;
}
node    : node7
seq     : 42
celsius : -3.5

The guard n != 3 is the whole safety net. Without it, a truncated packet would leave half the struct holding stale data and your control loop would act on it.

sscanf in C for Embedded Systems: Real Use Cases

A cellular modem answers the AT command for signal quality with a line such as +CSQ: 18,99. One sscanf call pulls out both numbers, and the literal prefix in the format doubles as a check that you really received that reply.

#include <stdio.h>

int main(void)
{
    const char *reply = "+CSQ: 18,99";
    int rssi = 0;
    int ber  = 0;

    if (sscanf(reply, "+CSQ: %d,%d", &rssi, &ber) == 2) {
        printf("signal index = %d, bit error = %d\n", rssi, ber);
        printf("approx power = %d dBm\n", -113 + 2 * rssi);
    } else {
        puts("unexpected modem reply");
    }
    return 0;
}
signal index = 18, bit error = 99
approx power = -77 dBm

The same pattern shows up in GPS receivers that emit comma-separated sentences, in bootloader command lines, in configuration lines such as baud=115200, and in test tools that read their expected values from a log. Whenever the text layout is fixed and short, sscanf is the quickest correct solution.

Embedded tip: on small microcontrollers the scanf family can add several kilobytes of flash. With newlib-nano, floating-point support in scanf is left out unless you link with -u _scanf_float, so a %f that works on your laptop may silently fail on the board. Check your toolchain’s documentation before relying on it, and consider strtol or strtof for tight memory budgets.

Common Mistakes With sscanf in C

MistakeWhat goes wrongFix
Forgetting & before a scalarsscanf writes through a garbage addressPass &value for int, float, double
%s with no widthInput longer than the array overflows itUse %7s for an 8-byte array
Ignoring the return valueBad input is treated as goodCompare against the expected count
%d with an input like 3.75Reads 3 and leaves .75 unreadUse %f, then check the rest
Using %lf for a float variableWrites 8 bytes into a 4-byte objectMatch the specifier to the exact type
Expecting %s to read a phraseIt stops at the first spaceUse %[^\n] or fgets

Best Practices, Performance and Security

  • Always give %s a maximum width that is one less than the array size.
  • Compare the return value with the exact number of fields you expect, not just “greater than zero”.
  • Initialise every destination variable so a failed match is easy to spot.
  • Treat text from a UART, network or file as untrusted. A missing width on %s is a classic remote buffer overflow.
  • sscanf re-reads the format string on every call and is slower than a hand-written loop. That is fine for a command typed once a second, but not for a hot interrupt handler.
  • Out-of-range numbers are undefined behaviour with sscanf. For strict range checking use strtol, which the next lecture covers.

Summary and Key Takeaways

  • sscanf reads formatted data from a string, scanf reads from stdin.
  • Pass an address for every conversion, except for arrays which already are addresses.
  • The return value counts successful conversions and is your validity check.
  • Literal characters in the format must match the input exactly.
  • %x handles hex with or without 0x, %s needs a width, and the specifier must match the variable type.
  • On small targets, check code size and float support before using it.

Conclusion

sscanf in C is a compact parser hiding inside the standard library. Used carefully, with widths on strings and a strict check of the return value, it turns messy text from sensors, modems and consoles into clean typed data in a single line. Used carelessly, it is a source of overflows and silent bad data. In the next lecture we build on this and validate input properly, so a typed letter where a number belongs is caught before it can do damage. Keep following this free C programming course and the rest of our free embedded C course to turn these building blocks into real firmware skills.

Frequently Asked Questions About sscanf in C

What does sscanf do in C?

sscanf reads formatted data from a string in memory and stores the converted values in the variables whose addresses you pass. It is the string-based version of scanf.

What does sscanf return?

It returns the number of fields converted and stored. It returns EOF if the input ends before the first conversion. Always compare it with the number of fields you expected.

What is the difference between scanf and sscanf?

scanf reads from standard input. sscanf reads from a string you supply. The format string and specifiers behave the same way.

Is sscanf safe to use?

It is safe when every %s has a width limit and you check the return value. Without those two habits it can overflow buffers and accept malformed data.

Can sscanf read hexadecimal numbers?

Yes. Use %x with an unsigned int variable. It accepts input with or without the 0x prefix.

Why does sscanf stop at the first space when reading a string?

%s reads only non-space characters. To read a phrase use %[^\n] with a width, or read the whole line with fgets first.

Does sscanf work on microcontrollers?

Yes, but it costs flash and may exclude floating-point support depending on the C library. Check your toolchain, and consider strtol for small targets.

Keep Going With the Free C Tutorial

Learn C programming for embedded systems step by step, with original examples and no cost. Next we make sscanf validate input.

💬 Need help or career guidance? Ask us!Contact Us →

2 Comments

Leave a Reply

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

×

🚀 BLE on Linux (BlueZ)

Hands-on course. Only ₹399

Enroll Now →