Input & Output with printf and scanf
Megaphones and Microphones
Every program needs to talk to the outside world. In C, printf is your megaphone β it shouts formatted output to the screen. scanf is your microphone β it listens for input from the keyboard and stores it in your variables.
Both use format specifiers β little codes starting with % that tell C what type of data to expect. Get the specifier wrong, and you'll see garbage on screen or crash your program.
Format Specifiers β The Rosetta Stone
Here are the format specifiers you'll use constantly:
%dor%iβint(decimal integer)%uβunsigned int%fβfloatordouble(in printf)%lfβdouble(required in scanf)%cβchar(single character)%sβ string (char array)%xβ hexadecimal,%oβ octal%pβ pointer address%zuβsize_t(result of sizeof)%%β literal percent sign
printf Basics
Formatting Output β Width & Precision
You can control exactly how your output looks. Between the % and the specifier letter, you can add numbers for width (minimum characters) and precision (decimal places).
Formatted Output
Escape Sequences
Special character combos that start with \:
\nβ newline (move to next line)\tβ tab (horizontal indent)\\β literal backslash\"β literal double quote inside a string\'β literal single quote\0β null character (string terminator)
Escape Sequences in Action
scanf β Reading Input
The scanf function reads formatted input from the keyboard. The critical rule: you must pass the address of a variable using the & operator. This is because scanf needs to know where in memory to store the value.
The one exception: arrays (including strings) already are addresses, so you don't need & with %s.
scanf Basics
1. Forgetting
& β scanf("%d", age) instead of scanf("%d", &age) won't give you an error in many compilers, but your program will crash or corrupt memory. Always use & for non-array variables!2. Buffer overflow with
%s β If the user types a 100-character name into a char name[10], you get a buffer overflow. Use %49s (one less than array size) to limit input: scanf("%49s", name).