Knowledge baseExam Center
ENEnglish
Choose language13

CKTIS / C

sscanf — read formatted data from a string

sscanf from <stdio.h> reads data from a null-terminated string according to a format. It stores results through pointers and returns the number of successful assignments (excluding `%n`), not the number of characters read.

Version: C23; repository compiler flag, production runtime not attested

Syntax

#include <stdio.h>
int sscanf(const char * restrict s, const char * restrict format, ...);

sscanf works like fscanf, but reads a string rather than a stream. The format describes conversions and required literal characters. %d requires int *; use &age. For the array name, pass name itself.

Check the return value before using the data: it counts successful assignments and can be smaller than expected or 0. A %n directive stores the number of characters read so far but does not increment the return value. EOF indicates an input failure before the first conversion completes. Successful assignments do not guarantee that the whole string was consumed.

%s skips leading whitespace, reads a word, and appends a null character. %7s needs at least 8 char elements. Most conversions skip leading whitespace; %c, %[ and %n do not.

An incompatible pointer type, a numeric result not representable in the destination object, or copying between overlapping objects causes undefined behavior. Field width does not provide numeric range checking. The example uses both results only after checking count == 2.

Examples

#include <stdio.h>

int main(void)
{
    const char input[] = "Ada 42";
    char name[8];
    int age;
    int count = sscanf(input, "%7s %d", name, &age);

    if (count != 2) {
        puts("Parse failed");
        return 1;
    }

    printf("%s: %d\n", name, age);
    return 0;
}

Result

Ada: 42

The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.

Sources