C - Standard Input Output

Use stdio.h for console input/output via printf, scanf, and related functions.

Learning Objectives

  • Use printf for formatted output.
  • Use scanf safely for input.
  • Handle input errors and buffer issues.

Prerequisites

Basic Input/Output

#include <stdio.h>

int main(void) {
  int age;
  char name[50];
  
  printf("Enter your name: ");
  if (scanf("%49s", name) == 1) {  // limit to prevent overflow
    printf("Enter your age: ");
    if (scanf("%d", &age) == 1) {
      printf("Hello %s, you are %d years old.\n", name, age);
    } else {
      printf("Invalid age input.\n");
    }
  }
}

Other stdio functions

#include <stdio.h>

int main(void) {
  char c;
  printf("Enter a character: ");
  c = getchar();  // reads one character
  printf("You entered: ");
  putchar(c);     // prints one character
  putchar('\n');
  
  char line[100];
  printf("Enter a line: ");
  if (fgets(line, sizeof line, stdin)) {
    printf("Line: %s", line);  // fgets preserves newline
  }
}

Common Pitfalls

  • Forgetting to pass the address (&x) to scanf.
  • Buffer overflow with unbounded %s - use %49s for a 50-char buffer.
  • Not checking return values of input functions.

Checks for Understanding

  1. Why do you pass &x to scanf?
  2. How do you safely read a string into a 50-character buffer?
Show answers
  1. scanf needs the address to modify the variable.
  2. Use scanf("%49s", buffer) or fgets(buffer, 50, stdin).