Lesson 69 +10 XP

User Input with scanf

User Input with scanf

Programs get exciting when they listen. scanf is how C reads what the user types.

The basics

#include <stdio.h>

int main() {
    int x;
    printf("Type a number: ");
    scanf("%d", &x);
    printf("The number typed is %d\n", x);
    return 0;
}

Wait, why the &?

In C, to let scanf change a variable, you hand it the variable's address with &. Don't worry - pointers are coming soon.

Reading several values

scanf("%d %f", &num, &grade);

Each format specifier grabs the next typed value.

Reading a character

char letter;
scanf("%c", &letter);

The golden rule

Match the specifier to the type: %d for int, %f for float, %lf for double, %c for char.

TL;DR

  • scanf("%d", &x) reads an integer into x.
  • The & passes the address so scanf can store the value.
  • Match specifiers to variable types.
  • Chained specifiers read several values.