C User Input

So far your programs have only shown output. But real programs also need to listen. In C, you read what the user types on the keyboard with the scanf() function. This page shows you how to capture numbers, characters, and text from the user and store them in variables.

Getting User Input

You already know printf() is used to print output. To do the opposite (read input) you use scanf(). Both functions live in the <stdio.h> header, so make sure you include it at the top of your file. When scanf() runs, the program pauses and waits for the user to type something and press Enter.

Read a number from the user

#include <stdio.h>

int main() {
  int age;
  printf("Enter your age: ");
  scanf("%d", &age);
  printf("You are %d years old.\n", age);
  return 0;
}
Note: Notice the & symbol before the variable name in scanf(). It means 'the address of'. scanf() needs to know WHERE in memory to store the value, so you give it the variable's address. Forgetting the & is one of the most common beginner mistakes in C.

The first argument to scanf() is a format specifier that tells C what kind of data to expect. This is the same idea you saw with printf(). Use %d for an integer, %f for a float, and %c for a single character. The second argument is the address of the variable where the value should be stored.

Common scanf format specifiers

SpecifierData typeExample variable
%dInteger (int)int count;
%fFloat (float)float price;
%lfDouble (double)double total;
%cSingle character (char)char grade;

Reading More Than One Value

You can ask for several values in a single scanf() call by listing multiple format specifiers and multiple addresses. When the user types the values separated by spaces (or Enter), C fills each variable in order.

Read two numbers and add them

#include <stdio.h>

int main() {
  int first, second;
  printf("Enter two numbers: ");
  scanf("%d %d", &first, &second);
  printf("The sum is %d\n", first + second);
  return 0;
}

Reading a Word of Text

To read text you use a char array (a string) with the %s specifier. Because the array name already refers to a memory address, you do NOT put an & before it. Keep in mind that %s reads only up to the first space, so it captures a single word, not a full sentence.

Read a name from the user

#include <stdio.h>

int main() {
  char firstName[30];
  printf("Enter your first name: ");
  scanf("%s", firstName);
  printf("Hello, %s!\n", firstName);
  return 0;
}
Note: Always make your char array big enough to hold the input plus one extra spot for the invisible terminating character C adds to the end of every string. If the user types more than the array can hold, the program can crash or behave strangely.

Exercise: C User Input

Why does scanf("%d", &age) require the & before age?