SyntaxStudy
Sign Up
C String Formatting and Parsing
C Beginner 1 min read

String Formatting and Parsing

The `printf` family of functions formats data into strings. `printf()` writes to standard output. `fprintf()` writes to a given `FILE *`. `sprintf()` and `snprintf()` write into a char buffer — always prefer `snprintf()` because it accepts a maximum length argument and prevents buffer overflows. The format string contains conversion specifiers like `%d`, `%s`, `%f`, and `%x` that are replaced with formatted argument values. The `scanf` family parses formatted input. `scanf()` reads from standard input, `fscanf()` from a file, and `sscanf()` from a string. The `sscanf()` function is particularly useful for parsing lines that were first read with `fgets()`. Always check the return value of `scanf` functions — they return the number of successful conversions, and a return value less than expected means the input was malformed. For more complex parsing, the `strtol()`, `strtod()`, and related functions convert string representations to numeric types. Unlike `atoi()` and `atof()`, the `strto*` functions detect errors through `errno` and a pointer to the first unconverted character. This makes them the correct choice for validating numeric input from files or users rather than blindly trusting the string is well-formed.
Example
#include <stdio.h>
#include <stdlib.h>
#include <errno.h>
#include <string.h>

int parse_int(const char *str, int *out)
{
    char *end;
    errno = 0;
    long val = strtol(str, &end, 10);
    if (errno != 0 || end == str || *end != '\0') return -1;
    *out = (int)val;
    return 0;
}

int main(void)
{
    /* snprintf: safe formatted string building */
    char buf[128];
    int  n = snprintf(buf, sizeof(buf),
                      "User: %-10s Age: %3d Score: %.2f",
                      "Alice", 30, 98.756);
    printf("snprintf wrote %d chars: \"%s\"\n", n, buf);

    /* sscanf: parsing a structured line */
    const char *line = "Bob 25 87.5";
    char   name[32];
    int    age;
    double score;
    int    parsed = sscanf(line, "%31s %d %lf", name, &age, &score);
    if (parsed == 3)
        printf("Parsed: name=%s age=%d score=%.1f\n", name, age, score);

    /* strtol: safe string-to-int with error detection */
    int value;
    const char *inputs[] = { "42", "  -17", "3.14", "99abc", "xyz" };
    for (int i = 0; i < 5; i++) {
        if (parse_int(inputs[i], &value) == 0)
            printf("'%s' -> %d\n",   inputs[i], value);
        else
            printf("'%s' -> parse error\n", inputs[i]);
    }

    return 0;
}