C:C Stdin Input: Using scanf(), fgets(), and sscanf() Safely
C•Stdin Parsing

C Stdin Input: Using scanf(), fgets(), and sscanf() Safely

Compilra executes C code using GNU GCC 14 with pre-supplied stdin sent before clicking Run. Always limit string lengths in scanf (like %63s) or read full lines with fgets() and sscanf() to prevent buffer overflows.

Syntax

if (scanf("%63s %d", name, &val) == 2) { ... }

Parameters & Values

Key components and acceptable values for this structure:

ParameterTypeDescription
scanf()intReads formatted tokens from stdin and returns the number of successfully matched items.
fgets()char*Reads up to size - 1 characters from stdin into a fixed buffer, stopping at newline or EOF.
sscanf()intParses formatted values safely from an in-memory line buffer already read via fgets().

Ready-to-Run Code Example

Executable in Compilra

Run this complete, working example directly without installing C locally:

#include <stdio.h>
#include <string.h>

int main(void) {
    int count = 0;
    if (scanf("%d", &count) != 1) return 0;

    for (int i = 1; i <= count; i++) {
        char name[64];
        int a = 0, b = 0, c = 0;
        if (scanf("%63s %d %d %d", name, &a, &b, &c) == 4) {
            printf("#%d %s: sum = %d\n", i, name, a + b + c);
        }
    }
    return 0;
}
Pre-Supplied Stdin (Input):
2
Ada 10 20 30
Grace 15 20 25
Expected Output:
#1 Ada: sum = 60
#2 Grace: sum = 60

How It Works: Step-by-Step

  • Lines 5-6: Reads the record count and checks scanf return value == 1 before looping.
  • Lines 9-12: Bounds string input to 63 chars (%63s) leaving room for the null terminator in char name[64].
  • Line 12: Prints each formatted record index, name, and integer sum.

Key Concepts

  • Supply all input lines in the Stdin panel before clicking Run—Compilra sends stdin upfront before launching the compiled C binary.
  • Checking scanf(...) == expectedCount protects your program from uninitialized variables on malformed or short input.
  • When records contain multi-word names with spaces, prefer fgets(line, sizeof(line), stdin) paired with sscanf().

Common Mistake: Using unbounded %s in scanf without a width limit

Writing scanf("%s", name) can write past the end of name[64], causing stack corruption or a SIGSEGV crash.

❌ Incorrect
char name[64];
scanf("%s", name); // Buffer overflow risk on long input
✅ Correct
char name[64];
if (scanf("%63s", name) == 1) { /* Bounded and checked */ }

Related C Tutorials & Compiler

Run and test C on Compilra

Execute this code snippet with pre-supplied standard input (stdin) in Compilra’s cloud compiler.

C Online Compiler