$ overview
overview/0x03·Foundations

Input & Output

Talking to the terminal with printf and scanf, and their format specifiers.

C has no built-in print statement — output is handled by ordinary library functions, the most common being printf and scanf, both declared in <stdio.h>. Both rely on a small template language called format specifiers to know how to interpret your data.

printf and format specifiers

printf.c
1#include <stdio.h>
2 
3int main(void) {
4 int age = 19;
5 float gpa = 3.8f;
6 char initial = 'N';
7 
8 printf("Age: %d\n", age);
9 printf("GPA: %.2f\n", gpa);
10 printf("Initial: %c\n", initial);
11 printf("%s is %d years old\n", "Nour", age);
12 return 0;
13}
  • %d — a signed integer.
  • %f — a floating-point number; %.2f rounds to 2 decimal places.
  • %c — a single character.
  • %s — a string (a char*, covered in 0x08).
  • %% — a literal percent sign.
warning: Mismatched specifiers are undefined behavior
Passing a double where printf expects an %d, or vice versa, compiles but produces garbage output — the compiler doesn't check this for you by default. Modern gcc will warn about it with -Wall, which is worth always enabling.

Reading input with scanf

scanf reads formatted input and needs the address of each variable it fills in, using the & operator (more on addresses in 0x09):

scanf.c
1#include <stdio.h>
2 
3int main(void) {
4 int age;
5 printf("Enter your age: ");
6 scanf("%d", &age);
7 printf("You are %d years old.\n", age);
8 return 0;
9}
note: Strings are the exception
A plain array already refers to its own address, so reading a string with scanf("%s", name) doesn't use &. This is explained fully once arrays and pointers connect in 0x0A.

Escape sequences

Inside string literals, a backslash introduces a special character:

escapes.c
1"\n" // newline
2"\t" // tab
3"\\" // a literal backslash
4"\"" // a literal double quote