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>23int main(void) {4int age = 19;5float gpa = 3.8f;6char initial = 'N';78printf("Age: %d\n", age);9printf("GPA: %.2f\n", gpa);10printf("Initial: %c\n", initial);11printf("%s is %d years old\n", "Nour", age);12return 0;13}
%d— a signed integer.%f— a floating-point number;%.2frounds to 2 decimal places.%c— a single character.%s— a string (achar*, 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>23int main(void) {4int age;5printf("Enter your age: ");6scanf("%d", &age);7printf("You are %d years old.\n", age);8return 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" // newline2"\t" // tab3"\\" // a literal backslash4"\"" // a literal double quote